Search code examples
excelprogramming-languageshex

convert negative decimal number into HEX


I must admit I don't remember much about HEX and so on from school (25 years ago). In any case, I have some values in decimal format which I need to convert into HEX. I am using Excel but I could write a function in VBA if necessary (or do it by code in VB.NET).

I already know how the HEX-result should look like (another source) but I need to use Excel to get this result exactly. The source of decimal input and also the result of the (right) HEX result is from a Linux-system if that is important to know.

Positive numbers seem to be converted correctly while negative numbers give me an headache in the sense that Excel adds in the beinning of the HEX two additional letters (two FF) compared to result I want.

Example: Decimal input: -524288

Correct HEX-output I must obtain: FFF80000

Using formula in Excel I get: FFFFF80000 (I get 2 FF extra in the beginning of the HEX-output)

Another example:

Decimal Input: -29446758

should be FE3EAD9A

but in Excel I get FFFE3EAD9A

It seems like I always get 2 extra FF in the HEX-output.

Can someone explain (in an easy way) why I get the 2 extra FF and if I can safely remove them?


Solution

  • In Excel, =DEC2HEX by default returns 10 characters.

    If you want to get just 8, as your question suggest use:

    =DEC2HEX(A1,8)
    

    Nevertheless, unless you have a compatibility issue, you may left the default numbers. Remember that the "F" char acts for negative numbers as a padding char (the same way "0" is for positive numbers).

    Edit

    The above fails for negatives, as you stated in your comment.

    The following works:

    =RIGHT(DEC2HEX(A1),8)