読者です 読者をやめる 読者になる 読者になる

Python | 2の補数のビットパターンを文字列で得る方法

str.format を使う
>>> '{:08b}'.format(-100 & 0xff)
'10011100'

>>> '{:02X}'.format(-100 & 0xFF)
'9C'

>>> '{:02X}'.format(-1000 & 0xFFFF)
'FC18'
int.to_bytes を使う
>>> b = (-100).to_bytes(1, byteorder='little', signed=True)
>>> b
b'\x9c'
>>> '{:02X}'.format(b[0])
'9C'

>>> b = (-1000).to_bytes(2, 'little', signed=True)
>>> b
b'\x18\xfc'
>>> '{:02X}{:02X}'.format(*b)
'18FC'

>>> b = (-1000).to_bytes(2, 'big', signed=True)
>>> b
b'\xfc\x18'
>>> lst = ['{:02X}'.format(x) for x in b]
>>> lst
['FC', '18']
>>> ''.join(lst)
'FC18'
struct を使う
>>> import struct
>>> b = struct.pack('b', -100)
>>> b
b'\x9c'
>>> '{:02X}'.format(b[0])
'9C'

>>> b = strckt.pack('h', -1000)
>>> b
b'\x18\xfc'
>>> '{:02X}{:02X}'.format(*b)
'18FC'

>>> b = strckt.pack('>h', -1000)
>>> b
b'\xfc\x18'
>>> lst = ['{:02X}'.format(x) for x in b]
>>> lst
['FC', '18']
>>> ''.join(lst)
'FC18'