如何从_bytes()计算整数?

2024-04-26 23:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解from_bytes()实际上做了什么

会议documentation mention this

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

但这并没有真正告诉我字节值是如何实际计算的。例如,我有一组字节:

In [1]: byte = b'\xe6\x04\x00\x00'

In [2]: int.from_bytes(byte, 'little')
Out[2]: 1254

In [3]: int.from_bytes(byte, 'big')
Out[3]: 3859021824

In [4]:

我尝试了ord(),它返回以下内容:

In [4]: ord(b'\xe6')
Out[4]: 230

In [5]: ord(b'\x04')
Out[5]: 4

In [6]: ord(b'\x00')
Out[6]: 0

In [7]:

我看不出12543859021824是如何从上面的值计算出来的

我还发现了this question,但它似乎并没有确切解释它是如何工作的

那么它是如何计算的呢


Tags: oftheinfromifbytesisorder
1条回答
网友
1楼 · 发布于 2024-04-26 23:45:14

大字节顺序与通常的十进制表示法类似,但以256为基数:

230 * 256**3 + 4 * 256**2 + 0 * 256**1 + 0 * 256**0 = 3859021824

就像

1234 = 1 * 10**3 + 2 * 10**2 + 3 * 10**1 + 4 * 10**0

对于小字节顺序,顺序相反:

0 * 256**3 + 0 * 256**2 + 4 * 256**1 + 230 = 1254

相关问题 更多 >