簡體   English   中英

將字節轉換為帶前導零的位

[英]convert bytes to bits with leading zeros

我知道我可以這樣做:

byte = 58

format ( byte , '08b' )


>>> '00111010'

我必須做兩個字節

format( bytes, '016b')

但如果我沒有字節數,我就無法為格式設置數字,所以我必須這樣做:

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

我想要這個而不使用任何循環

謝謝!

看起來您希望將整個文件內容打印為位字符串。

如果是這樣,你可以這樣做:

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

...或者...

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

...將使用更少的 memory

...或者...

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

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

...這避免了使用過多的風險的顯式循環 memory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM