How to convert a floating point number to a hexadecimal string in Perl?

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

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

for this purpose, and he will print 3fc3333333333333 for 0.15 . How to get a similar result in Perl ?

+7
floating-point perl
source share
1 answer

Perl pack () and unpack () functions allow you to display binary representations back and forth.

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

pack "d" packs double as its binary representation. Using unpack "Q" we unpack this bit pattern as an unsigned 64-bit integer. Thus, it reinterprets / discards the bitmap of the double number by an integer, which we can output with hexadecimal digits.

Perl also has the ability to format to display a hexadecimal floating point:

 printf "%a\n", 0.15; # Output: 0x1.3333333333333p-3 
+9
source share

All Articles