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


in reply to Hex Question(s)

Prepend '0x' to the string and it will maintain its numeric value.
#!/usr/bin/perl use strict; no warnings 'numeric'; my $this = sprintf("0x%x", 40); my $that = sprintf("0x%x", 2); my $other = $this + $that; printf "$other %x\n", $other; __END__ 42 2a
Update: Added no warnings for the -w happy...

Update: This is perl, v5.6.0 built for i386-linux

Replies are listed 'Best First'.
Re^2: Hex Question(s)
by Corion (Patriarch) on Mar 27, 2008 at 16:36 UTC

    I guess you didn't try your program:

    C:\>perl -w 676783.pl Argument "0x2" isn't numeric in addition (+) at 676783.pl line 8. Argument "0x28" isn't numeric in addition (+) at 676783.pl line 8. 0 0

    This oneliner shows that this isn't the case:

    >perl -le "print '0x42' + '0x10'" 0

    But of course, if you leave off the single quotes, Perl will interpret the numbers as numbers (in hexadecimal notation) and add them like it does add all numbers (regardless of their notation):

    >perl -le "print 0x42 + 0x10" 82

    ... but that's because internally, Perl does just see the numbers as numbers (without any representation to any base).

Re^2: Hex Question(s)
by TGI (Parson) on Mar 27, 2008 at 16:51 UTC

    What version of Perl are you using? When I run your code on my system (WinXP, ActivePerl 5.8.8), I get an incorrect answer. I added a the use warnings pragma to your code and got this result:

    C:\> test.pl Argument "0x2" isn't numeric in addition (+) at C:\test.pl line 9. Argument "0x28" isn't numeric in addition (+) at C:\test.pl line 9. 0 0

    You can specify hexadecimals in literal code by appending an '0x' to the value. I suppose, if you really wanted to get to a hexadecimal from a string, you could use string eval.

    my $this = sprintf("0x%x", 40); my $that = sprintf("0x%x", 2); my $other = eval "$this + $that"; printf "$other %x\n", $other;

    I'd be inclined to go with hex, though.


    TGI says moo

Re^2: Hex Question(s)
by deadlock (Initiate) on Mar 27, 2008 at 16:38 UTC
    perl -w test.pl Argument "0x2" isn't numeric in addition (+) at test.pl line 7. Argument "0x28" isn't numeric in addition (+) at test.pl line 7. 0 0