我正在尝试获取 b'\x00\x00\x00\x01' 的整数值,我假设应该是 1。
我已经尝试了几种方法来获得“1”这个值,但我得到的数字非常高。
这是我尝试过的:
import struct
from struct import *
#I had 4 int values:
byte1 = 0
byte2 = 0
byte3 = 0
byte4 = 1
#I packed each to one byte (seems weird, one int to 1 byte - so is this correct?)
byte1 = struct.pack('b', byte1) #returns b'\x00'
byte2 = struct.pack('b', byte2)
byte3 = struct.pack('b', byte3)
byte4 = struct.pack('b', byte4) #returns b'\x01'
#Now i place all those bytes in one container
con = byte1+byte2+byte3+byte4 #returns b'\x00\x00\x00\x01'
#hmm ..returns 4 - so seems alright?
len(con)
#tried several things:
struct.unpack('I', con) #unsigned int - returns 16777216 (what!?)
struct.unpack('i', con) #signed int - returns the same as above
unpack('I', con) #same ..
Run Code Online (Sandbox Code Playgroud)
我的问题; 难道我做错了什么?我理解错了吗?谁能向我解释为什么它不只是显示 '(1,)' ?
如果有另一种方法可以获得 int 代表。也请让我知道。
感谢您的阅读,感谢您的回复。
您将结果解释为小端,但您应该将其解释为大端。尝试
>>> con = b'\x00\x00\x00\x01'
>>> struct.unpack('>i', con)
(1,)
Run Code Online (Sandbox Code Playgroud)
使用正确的字节序。