Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert bytes to bits with leading zeros

I know that i can do this :

byte = 58

format ( byte , '08b' )


>>> '00111010'

with two bytes i have to do

format( bytes , '016b')

but if i doesn't have the number of bytes i can't set a number for format so i have to do :

with open('file','rb')as a:
    b = a.read()
    c = int.from_bytes ( b )
    d = format( c ,'b')
d = (8-len(a)%8)*'0'+d

but i was wondering if there was easier way to do this and i want this without using any loops

thanks!


2 Answers

You can map each byte to an 8-bit representation with the str.format method and then join the byte representations into a single string for output (where b is the bytes object you read from a file):

print(''.join(map('{:08b}'.format, b)))
like image 59
blhsing Avatar answered Oct 22 '25 18:10

blhsing


It looks as though you want the entire file content printed as a bit string.

If so, you could do this:

with open('foo.txt', 'rb') as bdata:
    print(''.join(f'{b:08b}' for b in bdata.read()))

...or...

with open('foo.txt', 'rb') as bdata:
    for b in bdata.read():
        print(f'{b:08b}', end='')
print()

...which will use less memory

...or...

def _format(b):
    return format(b, '08b')

with open('foo.txt', 'rb') as bdata:
    print(''.join(map(_format, bdata.read())))

...which avoids explicit loops at the risk of using too much memory

like image 37
Ramrab Avatar answered Oct 22 '25 17:10

Ramrab