Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

hex

perl

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".

like image 226
embedded Avatar asked Dec 05 '25 11:12

embedded


2 Answers

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
like image 82
tchrist Avatar answered Dec 08 '25 04:12

tchrist


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

sprintf("%x", 2001)
like image 30
Marcelo Cantos Avatar answered Dec 08 '25 03:12

Marcelo Cantos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!