将bytearray转换为int32

2024-06-28 19:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要关于如何将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写,但结果是完全不同的意思。Python代码:

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

输出为:

105437014618610837232953816530997152383565374241928549396796384452286402139811961128518

byteorder"little"时:

输出:

136519568683984449379607243264810023036788689642677418911039528254950904268659355108918

Tags: 代码bytesmainstatic建议consoleintguid
1条回答
网友
1楼 · 发布于 2024-06-28 19:49:22

您的代码实际上是采用前四个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

相关问题 更多 >