0

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 expected surface

But, instead I'm getting a surface that looks like this resultant surface (there is also a multiplier of 80 that explains why the numbers in the z-axis are so large)

jlt199
  • 2,349
  • 6
  • 23
  • 43
  • 3
    what do you mean by "doesn't make any sense" and "doesn't look right". Could you share some sample and show what is returned vs. what **should** be returned? In short a [mcve] would help a lot :) – MSeifert Jun 22 '17 at 20:41

2 Answers2

0

Some relative contents are already available here:

Python - Most effective way to implement two's complement?

and here:

Two's Complement in Python

AbhiAbzs
  • 134
  • 2
  • 12
  • Thanks, I've read most of them and that's where I've got my existing code from. Does `np.nditer(array, op_flags=['readwrite'])` do what I think it does? That is loop through every element of the array, updating the value by the result of the code in the loop – jlt199 Jun 22 '17 at 21:15
-1

Use this simple function

def twos_comp(val):
    return 0b111111111111 - val       # 12 ones

You may test it with

val = 0b111100001111
print("{:012b}".format(twos_comp(val)))

and you will got

000011110000

If it is not what you wanted, use this function instead

def twos_comp(val):
    return 0b1000000000000 - val      # 1 with 12 zeroes
MarianD
  • 13,096
  • 12
  • 42
  • 54