我試圖確保我擁有的一些數(shù)據(jù)被編碼為大端二進(jìn)制。我正在使用 struct 模塊來執(zhí)行此操作。但是,我將兩者都轉(zhuǎn)換為大端或小端的結(jié)果是相同的。為什么?import sysimport jsonimport structdata = { "val1": 20, "val2": 24}b = json.dumps(data, ensure_ascii=False).encode("utf-8")little = struct.pack(f"<{len(b)}s", b)big = struct.pack(f">{len(b)}s", b)print(f"System byteorder: {sys.byteorder}")print(f"data:\t")print(f"little:\t{little}")print(f"big:\t{big}")print((big == little) and (little == b))val = 25b = bytes([val])big = struct.pack(">H", val)little = struct.pack("<H", val)print()print()print(f"data:\t")print(f"little:\t{little}")print(f"big:\t{big}")print((big == little) and (little == b))給出以下結(jié)果System byteorder: littledata: b'{"val1": 20, "val2": 24}'little: b'{"val1": 20, "val2": 24}'big: b'{"val1": 20, "val2": 24}'Truedata: b'\x19'little: b'\x19\x00'big: b'\x00\x19'False
1 回答

大話西游666
TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
您正在使用格式說明符“s” char[]
,它只是一串八位字節(jié)。一串字符/八位字節(jié)沒有字節(jié)序。當(dāng)您使用“H”時(shí),unsigned short
您會(huì)看到大/小的順序相反。
添加回答
舉報(bào)
0/150
提交
取消