Search code examples
pythonbytebit32-bit

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 ?


Solution

  • 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