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
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With