Convert Bytes To Int?


Answer :

Assuming you're on at least 3.2, there's a built in for this:




int.from_bytes( bytes, byteorder, *, signed=False )



...



The argument bytes must either be a bytes-like object or an iterable
producing bytes.



The byteorder argument determines the byte order used to represent the
integer. If byteorder is "big", the most significant byte is at the
beginning of the byte array. If byteorder is "little", the most
significant byte is at the end of the byte array. To request the
native byte order of the host system, use sys.byteorder as the byte
order value.



The signed argument indicates whether two’s complement is used to
represent the integer.







## Examples:
int.from_bytes(b'\x00\x01', "big") # 1
int.from_bytes(b'\x00\x01', "little") # 256

int.from_bytes(b'\x00\x10', byteorder='little') # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) #-1024


Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.



>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04\x1a\xa3\xff'

>>> for b in bytelist:
... print(b) # 64 4 26 163 255

>>> [b for b in bytelist] # [64, 4, 26, 163, 255]

>>> bytelist[2] # 26


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable