I'm trying to get the integer value for b'\x00\x00\x00\x01', which should be 1 I assume.
I've tried several things to get this value of '1', but instead I get really high numbers.
This is what I tried:
import struct
from struct import *
#I had 4 int values:
byte1 = 0
byte2 = 0
byte3 = 0
byte4 = 1
#I packed each to one byte (seems weird, one int to 1 byte - so is this correct?)
byte1 = struct.pack('b', byte1) #returns b'\x00'
byte2 = struct.pack('b', byte2)
byte3 = struct.pack('b', byte3)
byte4 = struct.pack('b', byte4) #returns b'\x01'
#Now i place all those bytes in one container
con = byte1+byte2+byte3+byte4 #returns b'\x00\x00\x00\x01'
#hmm ..returns 4 - so seems alright?
len(con)
#tried several things:
struct.unpack('I', con) #unsigned int - returns 16777216 (what!?)
struct.unpack('i', con) #signed int - returns the same as above
unpack('I', con) #same ..
My question; Am I doing something wrong? Am I understanding something wrong? Can anyone please explain to me why it isn't just showing '(1,)' ?
If there's another way to get the int rep. please let me know too.
Thank you kindly for reading, and your reply.
1 Answer 1
You interpret the result as little endian, but you should interpret it as big endian. Try
>>> con = b'\x00\x00\x00\x01'
>>> struct.unpack('>i', con)
(1,)
to use the correct endianness.
3 Comments
<opinionated> Little endian is the One True Endianness. It puts bits 0-7 in byte 0, bits 8-15 in byte 1 and so on. Big endian was a historical mistake that resulted from the fact that we usually write numbers "in reverse", so that bit 0 comes in the last place. </opinionated>