Big byte-order is like the usual decimal notation, but in base 256:
230 * 256**3 + 4 * 256**2 + 0 * 256**1 + 0 * 256**0 = 3859021824
just like
1234 = 1 * 10**3 + 2 * 10**2 + 3 * 10**1 + 4 * 10**0
For little byte-order, the order is reversed:
0 * 256**3 + 0 * 256**2 + 4 * 256**1 + 230 = 1254
Answer from cffs on Stack Overflowpython - How is int.from_bytes() calculated? - Stack Overflow
python - Convert bytes to int? - Stack Overflow
int.to_bytes and int.from_bytes implementations incomplete
bytes -> int
Assuming you're on at least 3.2, there's a built in for this:
int.from_bytes(bytes,byteorder, *,signed=False)...
The argument
bytesmust either be a bytes-like object or an iterable producing bytes.The
byteorderargument determines the byte order used to represent the integer. Ifbyteorderis"big", the most significant byte is at the beginning of the byte array. Ifbyteorderis"little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, usesys.byteorderas the byte order value.The
signedargument 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
Hi,I am trying to rewrite some python lines to golang and I am stuck on converting byte array to int (little-endian byteorder)
python:
bytes1 = [84, 48, 92]bytes2 = [84, 48, 92, 91, 244]num1 = int.from_bytes(bytes1, "little")print(f"num1: ", num1)num2 = int.from_bytes(bytes2, "little")print(f"num2: ", num2)
gives me output:
num1: 6041684
num2: 1049504788564
and in golang :
`bytes1 := []byte{84, 48, 92}`
`bytes2 := []byte{84, 48, 92, 91, 244}`
`num1 := int(binary.LittleEndian.Uint16(bytes1))`
`fmt.Println("num1:", num1)`
`num2 := int(binary.LittleEndian.Uint32(bytes2))`
`fmt.Println("num2:", num2)`
I get:
num1: 12372
num2: 1532768340
can someone tell me what am I doing wrong ?