<?xml version="1.0" encoding="windows-1252"?>
<node id="849259" title="Convert big number from decimal to hexadecimal" created="2010-07-13 09:34:39" updated="2010-07-13 09:34:39">
<type id="1042">
CUFP</type>
<author id="295576">
ambrus</author>
<data>
<field name="doctext">
&lt;p&gt;
Today, [deMize] asked in the chatterbox how to convert the number 4335043554366887798866555766 to hexadecimal.  One solution is of course to use dc:
&lt;c&gt;
dc -e16o4335043554366887798866555766p
&lt;/c&gt;
&lt;p&gt;
The easiest perl solution is probably to use the Math::BigInt module:
&lt;c&gt;
perl -wE 'use Math::BigInt; say Math::BigInt-&gt;new("4335043554366887798866555766")-&gt;as_hex;'
&lt;/c&gt;
&lt;p&gt;
But here's another, more complicated solution.
&lt;c&gt;
perl -wE '
sub hadd { 
        no warnings "uninitialized"; 
        my($a, $b) = @_; my @b = @$b; my $c; 
        for (my $k = 0; @b || $c; $k++) { 
                $c = 16 &lt;= ($$a[$k] += $c + shift @b); $$a[$k] %= 16; 
        } 
} 
my $n = "4335043554366887798866555766"; 
my $h = []; for my $d (split //, $n) { 
        hadd $h, $h; hadd my $g = [], $h; hadd $h, $_ for $h, $h, $g, [$d]; 
} 
say join "", reverse map { sprintf "%x", $_; } @$h;
'
&lt;/c&gt;
&lt;p&gt;
&lt;b&gt;Update:&lt;/b&gt; deleted the unnecessary sub from the code.
&lt;!-- kw: bigint arithmetic engine, big integer, alu, long addition, number base conversion, radix conversion, arithmetic engine, fingers and toes, classical algorithms --&gt;
&lt;p&gt;
&lt;b&gt;Update 2011-03-18:&lt;/b&gt; see also [id://886513] for a list of bigint modules.
&lt;p&gt;
&lt;b&gt;Update 2012-08-25:&lt;/b&gt; see also [id://989716] for another conversion, this time to a more unusual number system.

</field>
</data>
</node>
