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!
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)))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With