Python | 2の補数 (signed) int ⇔ bytes ⇔ str (16進文字列)

(signed) int → bytes

int.to_bytes を使う
>>> (-100).to_bytes(1, byteorder='little', signed=True)
b'\x9c'

>>> (-1000).to_bytes(2, 'little', signed=True)
b'\x18\xfc'

>>> (-1000).to_bytes(2, 'big', signed=True)
b'\xfc\x18'
struct.pack を使う
>>> import struct
>>> struct.pack('b', -100)
b'\x9c'

>>> strckt.pack('h', -1000)  # little endian
b'\x18\xfc'

>>> strckt.pack('>h', -1000)  # big endian
b'\xfc\x18'

bytes → str (16進文字列)

>>> b = b'\x9c'
>>> '{:02X}'.format(b[0])
'9C'

>>> b = b'\xfc\x18'
>>> '{:02X}{:02X}'.format(b)
'FC18'

>>> lst = ['{:02X}'.format(x) for x in b]
>>> lst
['FC', '18']
>>> ''.join(lst)    # big endian
'FC18'

>>> lst.reverse()
>>> lst
['18', 'FC']
>>> ''.join(lst)    # little endian
'18FC'

str (16進文字列) → bytes

>>> n = int('9C', 16)
>>> n.to_bytes(1, byteorder='big')
b'\x9c'

>>> n = int('FC18', 16)
>>> n.to_bytes(2, byteorder='big')
b'\xfc\x18'

>>> n = int('18FC', 16)
>>> n.to_bytes(2, byteorder='little')
b'\xfc\x18'

bytes → (signed) int

int.from_bytes を使う
>>> int.from_bytes(b'\x9c', byteorder='big', signed=True)
-100

>>> int.from_bytes(b'\xfc\x18', 'big', signed=True)
-1000

>>> int.from_bytes(b'\x18\xfc', 'little', signed=True)
-1000
struct.unpack を使う
>>> import struct
>>> struct.unpack('b', b'\x9c')[0]
-100

>>> struct.unpack('>h', b'\xfc\x18')[0]  # big endian
-1000

>>> struct.unpack('h', b'\x18\xfc')[0]  # little endian
-1000