The function sprintf returns a string, and "0x3cb37140" is a string, while the bareword (in code) 0x3cb37140 is not - it is converted to a number. You can convert the string to a number with hex or eval. Also, adding and subtracting 0x1 doesn't give the result you expected:

use Devel::Peek; my $hex = sprintf( "0x%02x%02x%02x40", 60,179,113 ); print "\n\$hex as returned from sprintf:\n"; Dump($hex); my $num = hex $hex; print "\$hex hex()ed:\n"; Dump($num); $hex += 0x1; print "\$hex augmented with 0x01:\n"; print $hex,"\n"; __END__ $hex as returned from sprintf: SV = PV(0x8c90c20) at 0x8c90750 REFCNT = 1 FLAGS = (PADBUSY,PADMY,POK,pPOK) PV = 0x8cb34f0 "0x3cb37140"\0 CUR = 10 LEN = 12 $hex hex()ed: SV = IV(0x8cabcac) at 0x8c9078c REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 1018392896 $hex augmented with 0x01: 1

Strings are stored in a PV (pointer value) slot of a SV (scalar value), while integers get stored in the IV (integer value) slot of an SV. A variable can even carry both representations:

my $hex = sprintf("0x%02x%02x%02x40", 60,179,113); $hex = hex($hex); Dump($hex) __END__ SV = PVIV(0x84d3b10) at 0x84d1cdc REFCNT = 1 FLAGS = (PADBUSY,PADMY,IOK,pIOK) IV = 1018392896 PV = 0x84e5608 "0x3cb37140"\0 CUR = 10 LEN = 12

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

In reply to Re: convert hex string to hex number by shmem
in thread convert hex string to hex number by zentara

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.