Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (numbers)

Originally posted as a Categorized Question. Body may be blank.

  • Comment on How do I convert from decimal to hexidecimal?

Replies are listed 'Best First'.
Re: How do I convert from decimal to hexidecimal?
by tye (Sage) on Mar 08, 2001 at 23:41 UTC
Re: How do I convert from decimal to hexidecimal?
by jmcnamara (Monsignor) on Mar 09, 2001 at 14:58 UTC
    Use the X, x and # format codes in printf and sprintf:
        $num = 15;
    
        printf("%X\n",     $num);   # F
        printf("%x\n",     $num);   # f
        printf("%02x\n",   $num);   # 0f
        printf("%#x\n",    $num);   # 0xf
        printf("0x%02x\n", $num);   # 0x0f
    
    The last example is excessive but it forces formatting for zero:
        printf("%#x\n",    0);      # 0
        printf("0x%02x\n", 0);      # 0x00
    
    
Re: How do I convert from decimal to hexidecimal?
by line_noise (Sexton) on Apr 25, 2002 at 17:40 UTC
    Alternatively, to get the hex in a variable:

    $octet = 192; $out = pack "c", $octet; $hex = unpack "H2", $out;

    Edited by davido: Added code tags.

A reply falls below the community's threshold of quality. You may see it by logging in.