简体   繁体   中英

Pack and Unpack Bits and Bytes in Python

I am new to Python (I'm using Python3) and programming in general. Could you please provide a detailed explanation on how pack and unpack produce an answer in python; I know the syntax for using both functions but I do not understand how the answer is calculated. For example, I do not understand why the following code:

L = struct.pack('f', 255) print([ii for ii in L])

would produce the following output (especially why there is 127 and 67):

[0, 0, 127, 67]

Also, why the following code:

LL = struct.unpack('i', b'0000') print(LL)

would produce the following number:

(808464432,)

Thanks for the help.

In the first case you're seeing the decimal values of the 4 bytes that make up a 32bit floating point number .

In your specific example, the floating point number 255.0 is represented in memory as 4 bytes with hexadecimal values of 43 7f 00 00 . Since you're on a little-endian platform, you see the least significant byte first. Hence, converted into a list of bytes, you have

[ 0x00, 0x00, 0x7f, 0x43 ]

Converted to decimal values you obtain

[0, 0, 127, 67]

In the second case, you try to interpret the result of b'0000' .

>>> type(b'0000')
<class 'bytes'>
>>> len(b'0000')
4

As you can see, this expression returns a sequence of 4 bytes, so in this case it will be a sequence of 4 instances of the character 0 .

>>> '%x' % ord('0')
'30'

The value of the character 0 is 0x30 in hexadecimal. The 4 bytes interpreted as a 32bit integer are equivalent to the hexadecimal value of 0x30303030 .

>>> 0x30303030
808464432

When we write this value in decimal, we obtain 808464432 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM