Unpack function in python

I am trying to understand the decompression function in Python and how it uses a format string.

I use the format string "I", which as an example corresponds to unsigned int (size, 4 bytes).

According to the documentation, the decompression function will accept the string and convert it to a list of values ​​based on the format string.

http://docs.python.org/2/library/struct.html

So, I used the input value as a string, "test" and here is the result:

>>> import struct >>> input="test" >>> l = struct.unpack("I", input)[0] >>> print l 1953719668 

I am trying to understand how the output value was obtained from the input.

 >>> from struct import * >>> calcsize('I') 4 

the size of "I" is 4 bytes. the string "test" has 4 characters, which is 4 bytes. I tried to convert each character to the corresponding Hex ASCII value and save it in a small trailing order, but it does not match the output above.

Any help would be appreciated.

+4
source share
1 answer

Use 4s if you want to unzip the string as is.

 >>> struct.unpack('4s', 'test')[0] 'test' 

1953719668 obtained as follows: (small number)

 >>> ord('t') + (ord('e') << 8) + (ord('s') << 16) + (ord('t') << 24) 1953719668 
+5
source

Source: https://habr.com/ru/post/1491238/


All Articles