How is int.from_bytes() calculated?
Big byte-order is like the usual decimal notation, but in base 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
![Xantium](https://i.stack.imgur.com/72UbV.png?s=256&g=1)
Xantium
If my posts have been helpful to you remember you can up-vote or accept them. Or if my posts are incorrect or inaccurate please tell me by leaving a comment, and I will try to fix them as soon as possible. If you down-vote I would appreciate it if you please explain why, so that I may try and fix it. I appreciate any suggestions or improvements you might have. A man who is certain he is right is almost sure to be wrong. - Michael Faraday I am constantly learning new things and will continue to do so, though this great community. To all the members, askers, answerers, editors, reviewers and moderators, both old and new, who's hard work and dedication created, and continue to expand and maintain, this wonderful place. A big thank you My Github I am also on Discord DM me if you need a way to get hold of me. My username: Xantium#6468
Updated on June 08, 2022Comments
-
Xantium about 2 years
I am trying to understand what
from_bytes()
actually does.The 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.
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: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
or3859021824
was calculated from the values above.I also found this question but it does not seem to explain exactly how it works.
So how is it calculated?
-
Xantium about 6 yearsThank you, for helping me understand :-) You couldn't recommend any further reading on the subject could you?