I have to do a two's complement conversion of a 3D surface, each element representing a 12 bit two's complement number.
In order to convert the array I have the following code:
for x in np.nditer(array, op_flags=['readwrite']):
x[...] = twos_comp(x, 12)
where I found the following function online:
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val
However, the result I'm getting doesn't make any sense. Is my code wrong?
The other thing I have tried is:
for x in np.nditer(array, op_flags=['readwrite']):
if x > 2047:
x[...] = (2047 - x)
else:
x[...] = x
but again the data doesn't look "right". Any suggestions?
Thanks
By "not right" I mean that I'm expecting a surface that looks like
But, instead I'm getting a surface that looks like this (there is also a multiplier of 80 that explains why the numbers in the z-axis are so large)