Search code examples
perlperl-module

How to do formatted print of hex number with bigint/Math::BigInt?


I want to print hex numbers with a defined length, padded with zeros. The code below:

use warnings;
use bigint;
$x = 0x1_0000;
$y = 0x2_0000_12345;
print $x->as_hex(),"\n";
printf("%0#12x\n", $y);

produces the output:

0x10000
0x00ffffffff

But I would like the 2nd number to be 0x02000012345. It seems that bigint does not overload the format specifiers (if that is possible at all). Is there a good workaround?

Update: this seems to be a problem of the Perl installation. It should work as expected on a 64-bit version. This can be determined like below (from perldoc sprintf):

use Config;
if ($Config{use64bitint} eq "define" || $Config{longsize} >= 8) {
  print "Nice quads!\n";
}

Solution

  • A colleague pointed me to a solution using the BigInt::as_hex() function:

    printf("0x%016s\n", substr($x->as_hex(), 2));
    

    will print a 16-digit hex-number with padded 0s.