Convert negative value to Hex

Yesterday, my colleague came to me to ask a VB.Net code snippet for removing the front ‘F’s from a Hexadecimal number. I wondered and asked to him, why you want to remove the ‘F’s from the Hex. He explained that, ” I have a calculation which will return the resultant as negative value. If I convert the negative value into Hex and it will come like FFFF01395. But I want final result only 01395 “. After finished his explanation, I asked to him, if your final value may be F0D6 then what you will do. And I just told to him that removing ‘F’s is not the correct solution for your tasks.

So, we just googled like “negative int to hex” and got a forum link which where discussed about it. I wondered by seeing the solution. The below is the example they provided.

Scenario

Just take the Windows calculator and type -620 and convert it into Hex. The result is FFFFFFFFFFFFFD94. Then again without any changes just click Dec. The result must be -620. But the result is 18446744073709550996. Wow!!

Solution

= -620 + (2 ^ 16)                           [ 16 bit ]

= -620 + 65536

= 64916 (Base 10)

= FD94 (Hex Value)

So FD94 is the right answer.

I got new experience from him.

About these ads

One response to this post.

  1. Posted by Saravan on June 5, 2009 at 5:20 AM

    Wow!!

    Nice Solution.

    If the calculation in hex is 12475-1000000-1000+400 then the result would be FFFFFFFFFF011875 as displayed in windows calculator.

    Here what would be the Solution for the right answer.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: