2

I have a unsigned integer (32 bit), in which I've stored an n-bit signed number (2's complement, so -16 ≤ x < 16, and the resultant unsigned value is in the range 0-15).

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 0b1111 == -1

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

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Boris
  • 8,551
  • 25
  • 67
  • 120

1 Answers1

5

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,810
  • 1
  • 26
  • 45