mandalmanas5519 has asked for the wisdom of the Perl Monks concerning the following question:

# initialize a scalar variable with an integer value my $dec = 1211; print "Hexadecimal number: ", uc(sprintf("%x\n", $dec)), "\n"; # displays 4BB But how to get output in 000004BB format?
  • Comment on How to get hexadecimal output in specific format?

Replies are listed 'Best First'.
Re: How to get hexadecimal output in specific format?
by Tux (Canon) on Jun 05, 2013 at 05:41 UTC
    my $hex = sprintf "%08X", $dec;

    It is all in the docs

    $ perldoc -f sprintf : %X like %x, but using upper-case letters : 0 use zeros, not spaces, to right-justify

    Enjoy, Have FUN! H.Merijn
Re: How to get hexadecimal output in specific format?
by kcott (Archbishop) on Jun 05, 2013 at 05:49 UTC

    G'day mandalmanas5519,

    Welcome to the monastery.

    The documentation for sprintf has dozens of examples of how to compose the format and what the output looks like. So, for future reference, looking it up there would be a lot quicker than posting a question here and waiting for a reply.

    Here's how to compose the format for the specific instance you have here.

    1. % — start format (yes, you know this already)
    2. %0 — padding with zeros
    3. %08 — 8 characters
    4. %08X — uppercase hex digits (you don't need uc)
    $ perl -Mstrict -Mwarnings -E ' my $dec = 1211; say sprintf("%08x", $dec); say sprintf("%08X", $dec); ' 000004bb 000004BB

    -- Ken

Re: How to get hexadecimal output in specific format?
by rnewsham (Curate) on Jun 05, 2013 at 05:42 UTC

    Please use code tags around any example code, it will make your questions easier to read.

    Here is a slight tweak of your code that should do what you want.

    use strict; use warnings; my $dec = 1211; print "Hexadecimal number: ", uc(sprintf("%08x\n", $dec)), "\n";