How do I convert a decimal number to a hex string in Perl?

15,298

Solution 1

This works for that case:

($x,$y) = map { "0x$_" } 
          sprintf("%04X\n", 2001) =~ /(..)(..)/; 

But I wonder what you're really trying to do. If you're trying to get UTF-16, this isn't the way you want to do that.

If you're trying to figure out the layout of packed binary data, then you should be using unpack. The "C4" format would work for a 4-byte integer.

$int = 2001;
$bint = pack("N", $int);
@octets = unpack("C4", $bint);
printf "%02X " x 4 . "\n", @octets;
# prints: 00 00 07 D1

For some purposes, you can use printf's vector print feature:

printf "%v02X\n", pack("N", 2001);
# prints: 00.00.07.D1

printf "%v02X\n", 255.255.255.240;
# prints: FF.FF.FF.F0

Solution 2

I'm not sure what exact format you want it in, but one way to convert to hex is:

sprintf("%x", 2001)
Share:
15,298
embedded
Author by

embedded

Updated on June 04, 2022

Comments

  • embedded
    embedded almost 2 years

    How do I convert a decimal number to a hex string in Perl?

    For example, I would like to convert 2001 into "0x07" and "0xD1".

  • embedded
    embedded over 13 years
    This not quite good for me. I need to convert each byte to hex string.
  • Alex S
    Alex S over 13 years
    What you are trying to do is somewhat awkward. If you describe what you are trying to achieve at a higher level, an alternative strategy might occur to someone.
  • embedded
    embedded over 13 years
    I need to fill in a struct in C. therefore I need to be able to write a script that breaks each byte of an int to hex string byte.
  • embedded
    embedded over 13 years
    This is quite good, could you please generalize it a bit and not only for 2 bytes numbers. I've changed ($x,$y) to @arr, what about the =~ /(..)(..)/?
  • Alex S
    Alex S over 13 years
    Are you trying to generate C code, or simply construct the bytes of a C struct? If it's the latter, then use pack("S", 2001).
  • Peter Mortensen
    Peter Mortensen almost 9 years
    No, this will not output as "07D1". "%x" will output in lower case. Use "%X" for the correct uppercase.