http://qs321.pair.com?node_id=75607

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";