Difference between ASM/C++ and Python when NEG unsigned 1

0

I recently stumbled at an error which is present only in Python.
Negating unsigned 1 does not equal FFFFFFFF.

In Assembler:

MOV(eax, 0x1)
NEG(eax)

Result is 0xffffffff

Same result in C++

In Python however:

import numpy as np
print(hex(~np.uint32(1)))

Result is 0xfffffffe

What am I missing here?

python
asked on Stack Overflow Sep 8, 2020 by Involar

1 Answer

0

In two's complement arithmetic, negation requires taking the bitwise inversion of a number (which is what ~ does) and adding one to it.

print(hex(~np.uint32(1) + 1))

Or you could use Python's negation operator:

print(hex(-np.uint32(1)))
answered on Stack Overflow Sep 8, 2020 by Mark Ransom

User contributions licensed under CC BY-SA 3.0