### Hex to decimal

by Ras (Acolyte)
 on Apr 26, 2001 at 00:27 UTC Need Help??
Ras has asked for the wisdom of the Perl Monks concerning the following question:

How can i convert a hex to a short signed decimal? For example: Convert hex AA into dec -86. How can i do this using perl?

Replies are listed 'Best First'.
(tye)Re: Hex to decimal
by tye (Sage) on Apr 26, 2001 at 01:06 UTC

See hex.

```my \$hex= "FFAA";
my \$unsigned= hex(\$hex);
my \$signed= \$unsigned;
\$signed -= 0x10000   if  \$signed & 0x8000;

- tye (but my friends call me "Tye")
Re: Hex to decimal
by busunsl (Vicar) on Apr 26, 2001 at 00:28 UTC
Have a look at the unpack function.

perdoc -f unpack

I'm sorry i made an mistake i want to convert hex FFAA into dec -86. How can i do this using perl and please can you show me some syntax?

```D:\Perl\dl>perl -e "print unpack('s',pack 's', hex('ffaa'))"
-86
This:
• takes the string 'ffaa' and makes a decimal value with hex
• packs that value into a signed short
• unpacks that structure as a signed short
• and prints it

--
I'd like to be able to assign to an luser

\$signed = (hex(ffaa)^0x8000)-0x8000;
Re: Hex to decimal
by turnstep (Parson) on Apr 26, 2001 at 00:31 UTC

Don't forget the online documentation here at perlmonks too: you can add an instant unpack and even a pack link to your replies. :)

Re: Hex to decimal
by TeKk9 (Scribe) on Apr 26, 2001 at 00:46 UTC
You can try a sprintf ie.
```\$num = "AA";
\$dec_num = sprintf("%d", hex(\$num));
print "\$dec_num\n";

Create A New User
Node Status?
node history
Node Type: perlquestion [id://75607]
Approved by root
help
Chatterbox?
 Discipulus was a question [GotToBTru]: current job found me Discipulus is so lucky to have a decent job, with old, favorable contract, done before the ultralibersm arrived in Eataly [Lady_Aleena]: Has anyone here ever use pcregrep? I can't seem to get the --include regex right. --include=*.p[lm] works in grep but not pcregrep. [erix]: to lift your spirits, here is some more happy Randy news... [Lady_Aleena]: The reason I would like to use pcregrep is because it can do multiline searches supposedly. [perldigious]: What are your criteria for looking Tanktalus? What things must a job have for you to consider it? And where are you in your career? Start, middle, or end? [erix]: are there any regex-engines that do not do multiline? [Lady_Aleena]: erix, grep doesn't. [Lady_Aleena]: Linux grep that is...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2017-05-23 19:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favorite model of computation is ...

Results (181 votes). Check out past polls.