1

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.

asked Apr 19, 2012 at 11:52

1 Answer 1

5

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.

answered Apr 19, 2012 at 11:54
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, this works indeed. But I thought little endian starts reading from the right. Anyhow, thanks alot.
Little endian is the "reversed" one where the most significant byte comes last.
@joey: <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>

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.