简体   繁体   English

用Python打包位和字节

[英]Pack and Unpack Bits and Bytes in Python

I am new to Python (I'm using Python3) and programming in general. 我是Python(我正在使用Python3)和编程的新手。 Could you please provide a detailed explanation on how pack and unpack produce an answer in python; 您能否详细说明如何打包和解包在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): 会产生以下输出(尤其是为什么有127和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 . 在第一种情况下,您将看到组成一个32位浮点数的4个字节的十进制值。

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 . 在您的特定示例中,浮点数255.0在内存中表示为4个字节,十六进制值为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' . 在第二种情况下,您尝试解释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 . 如您所见,该表达式返回4个字节的序列,因此在这种情况下它将是字符0的4个实例的序列。

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

The value of the character 0 is 0x30 in hexadecimal. 字符0的值是十六进制的0x30 The 4 bytes interpreted as a 32bit integer are equivalent to the hexadecimal value of 0x30303030 . 解释为32位整数的4个字节等效于十六进制值0x30303030

>>> 0x30303030
808464432

When we write this value in decimal, we obtain 808464432 . 当我们用十进制写这个值时,我们得到808464432

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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