简体   繁体   English

如何计算int.from_bytes()?

[英]How is int.from_bytes() calculated?

I am trying to understand what from_bytes() actually does. 我试图了解from_bytes()实际作用。

The documentation mention this : 文档中提到了这一点

The byteorder argument determines the byte order used to represent the integer. byteorder参数确定用于表示整数的字节顺序。 If byteorder is "big", the most significant byte is at the beginning of the byte array. 如果byteorder为“ big”,则最高有效字节在字节数组的开头。 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. 要请求主机系统的本机字节顺序,请使用sys.byteorder作为字节顺序值。

But this does not really tell me how the bytes values are actually calculated. 但这并不能真正告诉我如何实际计算字节值。 For example I have this set of bytes: 例如,我有这组字节:

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]:

I tried ord() and it returns this: 我尝试过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]:

I don't see how either 1254 or 3859021824 was calculated from the values above. 我看不到如何从上述值中计算出12543859021824

I also found this question but it does not seem to explain exactly how it works. 我也找到了这个问题,但似乎并不能完全解释它是如何工作的。

So how is it calculated? 那么如何计算呢?

Big byte-order is like the usual decimal notation, but in base 256: 大字节顺序类似于通常的十进制表示法,但以256为基数:

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

just like 就像

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

For little byte-order, the order is reversed: 对于小字节顺序,顺序相反:

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

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

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