+0  
 
0
1
6122
2
avatar

how to convert hexadecimal to signed integer?

 Jun 19, 2015
 #2
avatar
+5

In the most common system for signed integers, "two's complement", the most significant bit is the sign-bit and the rest work up positively. This basically means the first bit is considered a negative, and the rest are positive. In a byte thats -128 to 127 (0 is included in the positives)

Example:

10010101 = [-10000000] + [00010101] = -128 + 21 = -107

The same would apply to Hexadecimal simply by making the most significant nibble (4 bits) contain the sign-bit (This is making negative integers when the most significant nibble is an 8, 9 or A to F) and treat the rest of the hexadecimal value as part of the integer.

Example:

9E = 1001 1110 = [-1000 0000] + [0001 1110] = -128 + 30 = -98

The best conversion I can see would be to convert the hexadecimal into binary, and then convert back into integer (Most significant bit as a negative) by use of the 2 to the power of the bit's position (The least significant as position 0)

Example:

AE 

1010 1110

-(2^7) + (2^5) + (2^3) + (2^2) + (2^1)

-128 + 32 + 8 + 4 + 2 = -128 + 46 = -82

 

Unfortunately, this doesn't take into account other ways of doing signed-ness on binary. However a generally easy thing to think about is treat hexadecimal as it's binary form (Or at least the first character) and work from there.

 Jun 19, 2015

0 Online Users