• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1857

# Converting signed hex back to a decimal???

Hi all, just wondering how to convert a hex number which is negative to it's decimal equivalent.

So if I had the number '0xFE' it would output it's decimal number (which would have originally been negative).

Any ideas?
0
OnlyOne
• 2
1 Solution

Commented:
You want to use the hex() function; however, hex("0xFE") would return 254, not -2 (as I assume you would like).  On the other hand, hex("0xFFFFFFFE") still returns 4294967294, not -2.

If you need to enforce signed-ness, that's a different story.  Assuming you have an eight-character hex number (like "FFFFFFFE"), you can use the following code:

\$number =
unpack "i",      # decode as a signed integer
pack "I",        # encode as an unsigned integer
hex("0x\$hnum");  # convert 0x........ to integer

When I set \$hnum to "FFFFFFFE", I get -2 in \$number.
0

Commented:
I just realized that if you have a two-character hex value, such as "FE", you can use the "c" and "C" pack/unpack template.

\$number =       # so it gets -2
unpack "c",   # unpacked as signed char
pack "C",     # packed as unsigned char
hex("0xFE");  # returns 254
0

Commented:
OnlyOne,

"..convert a hex number which is negative to it's decimal equivalent...."

Here is a small script that might work for you.

#!/usr/local/bin/perl

print \$number,"\n";

Hope that helps.

"..(which would have originally been
negative)..."

i am not sure if the above code solves this part.
0

Author Commented:
Well done, japhyRPI, that was right on the money.

Keep up the good work!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.