Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a floating-point number into a hex string in Perl?

To be quite certain that my calculations are correct for all cases, I want to see the result (a double precision number) as a hex or binary string. How can I get a hex/binary string or a byte representation of this number in Perl? In Java, I could use, for instance,

double d = performMyCalculations();
System.out.format("%x\n", Double.doubleToLongBits(d));  

for this purpose, and it will print 3fc3333333333333 for 0.15. How can I get a similar result in Perl?

like image 209
m. vokhm Avatar asked Dec 17 '17 10:12

m. vokhm


1 Answers

Perl's pack() and unpack() functions allow you to cast binary representations back and forth.

my $double_bits = unpack "Q", pack "d", 0.15;
printf "%x\n", $double_bits;
# Output: 3fc3333333333333

The pack "d" packs a double as its binary representation. With unpack "Q" we unpack this bit pattern as an unsigned 64-bit integer. So this reinterprets/casts the bit pattern of a double to an integer, which we can then output with hex digits.

Perl also has a formatting option to display hexadecimal floating point:

printf "%a\n", 0.15;
# Output: 0x1.3333333333333p-3
like image 90
amon Avatar answered Sep 21 '22 17:09

amon