简体   繁体   中英

Reversing byte order of negative integer with Python 3

After extracting some 32-bit sign bit value and keeping that same 32-bit representation sign-extended, I now have to reverse the byte order of the value (I need to follow a precise imposed workflow).

Here is what I previously did:

  • initially I have the value "11101101111110100111001110011010"
  • I converted that chain to int : I get 3992613786
  • I extracted the 32-bit sign bit (sign-extended): I get -302353510

Now, I have to reverse the byte order of that last value (I am supposed to get -1703675155 in the end).

Does anyone know how to reverse the byte order of a negative extended sign bit with Python3?

There are probably better ways but this seems to work:

from struct import pack

x = "11101101111110100111001110011010"

n = ((~int(x, 2) + 1) & 0xffffffff) * -1 if x[0] == '1' else 1


print(int.from_bytes(pack('!i', n), 'little', signed=True))

Output:

-1703675155

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