1

Lets say I have a integer (32 bit), which stores a n-bit unsigned number (with n < 32). How can I transform this efficiently into a signed interpretation using the two's complement?

A short example to clarify what I mean:

int numUnsigned = 15; // Store a 4-bit value 0b1111
int numSigned = ???; // Convert to 4-bit signed value using two's complement
// Now numSigned should be -1, since 0b111 == -1

I've been messing with the bits all morning but can't seem to get it right.

Boris
  • 8,065
  • 23
  • 61
  • 117

1 Answers1

3

If I understood your question correctly, you just need a sign extension and not 2's complementary (at least according to your comment in the second line of code).

If I am correct, you can do the following (Let's assume you have N digits, 0 < N < 32):

unsigned msb_mask = 1 << (N-1); // setup a mask for most significant bit
numSigned = numUnsigned;
if ((numSigned & msb_mask) != 0) // check if the MSB is '1'
{
    numSigned |= ~(msb_mask-1); // extend the MSB
}

Maybe I misunderstood your question... If so then just ignore my answer.

EDIT

Suggested by @harold :

numSigned = (numUnsigned^msb_mask)-msb_mask ;
Alex Lop.
  • 6,740
  • 1
  • 27
  • 44