0

Unpack from struct python

Hello there! I want to trun some bytes into integer form. I use the code but if i remove the '!' before 'hhl' then the result is not true. What is the reason? 'a' should be 1 2 3 from struct import * a =unpack('! hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') print(a)

19th Jul 2018, 7:22 PM
Aref moloughi
Aref moloughi - avatar
2 ответов
+ 1
Exclamation mark determines the byte order. In your case it is used to represent data in network byte order, because the byte sequence was packed that way . In other words, if you'd have another byte order, you could use format string without '!': >>> a = unpack('hhl', b'\x01\x00\x02\x00\x03\x00\x00\x00') >>> a (1, 2, 3) So, the byte sequence should have been packed using 'hhl' fomat string to keep the "traditional" order: >>> b = pack('hhl',1,2,3) >>> b b'\x01\x00\x02\x00\x03\x00\x00\x00'
20th Jul 2018, 10:11 AM
strawdog
strawdog - avatar
0
So if i want communicate with network it's sth like htons()? It checks my host byte order and since network byte order is big endian , if my host be little endian then it fixes the order from big endian to little endian otherwise it's a no op. Am i right? Or maybe it does not check my host byte order. It only changes the byte order. I must first realize if my host byte order and network byte order are different then use it. Which one is true?
20th Jul 2018, 10:50 AM
Aref moloughi
Aref moloughi - avatar