byte to int python code example
Example 1: python bytes to int
"""
Python 3
"""
someBytes = b'\x00\x01\x00\x02\x00\x03'
someInteger = int.from_bytes(someBytes)
someInteger = int.from_bytes(someBytes, 'big')
someInteger = int.from_bytes(someBytes, byteorder='little', signed=True)
"""
Python 2.7
"""
import struct
struct.unpack(pattern, someBytes)
>>> import struct
>>> sixBytes = b'\x00\x01\x00\x02\x00\x03'
>>> struct.unpack('>HHH', sixBytes)
(1, 2, 3)
>>> struct.unpack('<HHH', sixBytes)
(256, 512, 768)
>>> struct.unpack('>BBBBBB', sixBytes)
(0, 1, 0, 2, 0, 3)
>>> struct.unpack('<BBBBBB', sixBytes)
(0, 1, 0, 2, 0, 3)
Example 2: convert int to byte python
pythonCopy>>> (258).to_bytes(2, byteorder="little")
b'\x02\x01'
>>> (258).to_bytes(2, byteorder="big")
b'\x01\x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'\x02\x01\x00\x00'
>>> (-258).to_bytes(4, byteorder="little", signed=True)
b'\xfe\xfe\xff\xff'