As davido points out, sprintf() would be almost good enough on its own.

$ perl -le 'printf( "%04x\n", 12)' 000c

And, as he points out, you can get the rest of the way with s///. That's pretty ugly though. You could also get there a few other ways... but they are all pretty ugly.

It would be nice if you could have something like

perl -le 'printf( "\\x%02x\\x%02x\n", 12 )' # WRONG \x0c\x00

Unfortunately, "12" is one argument, not two. But that's where unpack comes in handy. You want to unpack a number into two (char sized) values. That leads you to

perl -le 'printf( "\\x%02x\\x%02x\n", unpack( "C2", 12 ))' WRONG \x31\x32

But that's wrong too as 12 is a scalar and gets unpacked (by that) as "1", "2" (ASCII 0x31 and 0x32 respectively.) And this is where pack is useful. You want to pack that 12 into a single value before unpacking it into two. Two characters is a short...

perl -le 'printf( "\\x%02x\\x%02x\n", unpack( "C2", pack("S", 12)))' \x0c\x00

Oops. Still not quite right. My architecture is little-endian (x86). But that's okay, we can force pack to give us a big-endian short.

perl -le 'printf( "\\x%02x\\x%02x\n", unpack( "C2", pack("n", 12)))' \x00\x0c # Another way to say that . . . perl -le 'printf( "\\x%02x\\x%02x\n", unpack( "C2", pack("S>", 12)))' \x00\x0c

It might not be beautiful, but I think it's better than futzing about with string operations after the conversion to hex. Of course, if you read perlpacktut as suggested, I'm sure you've come to this solution already! ;-)

-sauoq
"My two cents aren't worth a dime.";

In reply to Re: Convert to Hexadecimal by sauoq
in thread Convert to Hexadecimal by Anonymous Monk

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.