簡體   English   中英

將字節數組轉換為 int32

[英]Convert bytearray to int32

我需要有關如何將 GUID 轉換為byteArray然后將其轉換為int 在以下 C# 代碼中,一切正常。

static void Main(string[] args)
    {
        var str = "6F9619FF-8B86-D011-B42D-00CF4FC964FF";
        byte[] bytes = Encoding.ASCII.GetBytes(str);
        int result1 = BitConverter.ToInt32(bytes, 0); 
        Console.WriteLine(result1);
        Console.ReadLine();
    }

這個程序的輸出是909723190

想用python3寫,結果卻是完全不同的意思。 蟒蛇代碼:

s = "6F9619FF-8B86-D011-B42D-00CF4FC964FF"
b = bytearray()
b.extend(map(ord,s))
int.from_bytes(b, byteorder="big")

輸出是:

105437014618610837232953816530997152383565374241928549396796384452286402139811961128518

byteorder"little"

輸出:

136519568683984449379607243264810023036788689642677418911039528254950904268659355108918

您的代碼本質上是采用前四個 ascii 值:

"6F96" => [x36, x46, x39, x36]

然后將這 4 個字節以 little endian 作為整數插入:

因此, 0x36394636 == ‭909723190

Python等價物:

>>> s = "6F9619FF-8B86-D011-B42D-00CF4FC964FF"
>>> val = (ord(s[3]) << 24) | (ord(s[2]) << 16) | (ord(s[1]) << 8) | ord(s[0])
>>> val
909723190

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM