Thursday, September 18, 2008

Easy way to convert negative integers to hexadecimal

If you came here looking for some magic......sorry .... I had some issues representing negative integers in hex. Every time I had to convert them to binary, do a 2's complement and then reconvert to hex :-( so was looking for a way which I could use to quickly do my job. I got this trick from net and thought it is pretty easy. You just need to keep the following mapping in mind (or paper :-) though it is pretty simple).

0 1 2 3 4 5 6 7
F E D C B A 9 8

that's all. The above table is just numbers 1-15 in clockwise direction, or more technically the upper number is inverse of the below one.

Now to convert any number say -7218, follow below steps :-

a) Convert 7218 to hex = 0x1C32
b) Interchange each digit with its corresponding counter bit from mapping = 0xE3CD
c) Shift the last digit to left by 1 place...so D becomes E = 0xE3CE = -7218 = 0xFFFFE3CE (don't forget to fill it with 'F's on left. If you don't fill it with 'F' it becomes 65536-7218 = 58318)

NOTE : If the last digit is 'F' and you shift left, you go to '0' and then shift the next digit to left. (Much like carry over).

No comments: