Jennan
Jennan

Reputation: 89

converting a hexadecimal number correctly in a decimal number (also negatives)

As the headline supposes I am trying to convert hex numbers like 0x320000dd to decimal numbers. My code only works for positive numbers but fails when it comes to hex numbers that represent negative decimal numbers. Here is a excerpt of my code:

         cin>>hex>> x;
         unsigned int number = x;
         int r = number & 0xffffff; 

My input is alreay in hex, and the computer converts it automatically in an integer. What I am trying to do is getting the operand of the hex number, so the last 24 bits. Can you help me get my code working for negative values like :0x32fffdc9 or 0x32ffffff? Thank's a lot!

EDIT:

I would like my output to be : 0x32fffdc9 --> -567 or 0x32ffffff --> -1

so just the plain decimal values but instead it gives me 16776649 and 16777215 for the upper examples.

Upvotes: 1

Views: 1601

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38919

Negative integers are typically stored in 2's complement Meaning that if your most significant bit (MSB) is not set the number is not negative. This means that just as you need to unset the 8-MSBs of your number to clamp a 32-bit number to a 24-bit positive number, so you'll need to set the 8-MSBs of your number to clamp to a negative number:

const int32_t r = 0x800000 & number ? 0xFF000000 | number : number & 0xFFFFFF;

vector<bool> or bitset may be worth your consideration, as they would clarify the hexadecimal numbers to the range of bits to be set.

Upvotes: 2

Related Questions