Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Hex Question(s)

by YuckFoo (Abbot)
on Mar 27, 2008 at 16:28 UTC ( #676783=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Hex Question(s)
Download Code
Re^2: Hex Question(s)
by Corion (Pope) 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 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
Re^2: Hex Question(s)
by TGI (Vicar) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://676783]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2014-11-01 11:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (229 votes), past polls