John Smith
John Smith

Reputation: 283

How would you unpack a 32bit int in Python?

I'm fairly weak with structs but I have a feeling they're the best way to do this. I have a large string of binary data and need to pull 32 of those chars, starting at a specific index, and store them as an int. What is the best way to do this?

Since I need to start at an initial position I have been playing with struct.unpack_from(). Based on the format table here, I thought the 'i' formatting being 4 bytes is exactly what I needed but the code below executes and prints "(825307441,)" where I was expecting either the binary, decimal or hex form. Can anyone explain to me what 825307441 represents?

Also is there a method of extracting the data in a similar fashion but returning it in a list instead of a tuple? Thank you

st = "1111111111111111111111111111111"
test = struct.unpack_from('i',st,0)
print test

Upvotes: 0

Views: 1486

Answers (1)

C.B.
C.B.

Reputation: 8336

Just use int

>>> st = "1111111111111111111111111111111"
>>> int(st,2)
2147483647
>>> int(st[1:4],2)
7

You can slice the string any way you want to get the indices you desire. Passing 2 to int tells int that you are passing it a string in binary

Upvotes: 4

Related Questions