简体   繁体   中英

Convert bytearray to int32

I need advice on how to convert a GUID to a byteArray and then convert that to and int . In the following C# code, everything works out correctly.

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();
    }

Output of this program is 909723190 .

I want to write it in python3, but the result is a completely different meaning. Python code:

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

Output is:

105437014618610837232953816530997152383565374241928549396796384452286402139811961128518

When byteorder is "little" :

Output:

136519568683984449379607243264810023036788689642677418911039528254950904268659355108918

What your code is essentially doing is taking the first four ascii values:

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

And then interpeting these 4 bytes in little endian as an integer:

Hence, 0x36394636 == ‭909723190

Python equivalent:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM