in reply to Converting an array of bytes into a BigInt - speed considerations

I had some problems with earlier examples. So I cobbled up my own version which should work for any N-bit (16, 32, 64, etc) PC.

use strict; use Math::BigInt; ############################ # BEGIN N-BIT SYSTEM CHECK # ############################ # Calculate the bit-width of cells on this system. sub count_bits { my $i = 0; my $q = ~0x0; # Set all bits while ( $q ) { # All shifted out? $q = $q << 1; # Shift left $i++; # Accum shifts } return $i; # Return bit-width } my $bits = count_bits; # System bit-width. my $cells = int( $bits / 8 ); # max bytes in array my $mask = ~0x0; # Full mask = 0xF* my $top_bit = ~( $mask >> 1 ); # High mask = 0x80* ########################## # END N-BIT SYSTEM CHECK # ########################## # Convert a BigInt to an array. sub bint_to_array { my $quo = shift; my $msk = Math::BigInt->new($mask); my @cls; until ( $quo->is_zero() ) { my $rem = $quo->copy(); # Lest modify ruin. $rem->band($msk); # REM = LSC $quo->brsft($bits); # QUO = Cells above unshift @cls, $rem->bstr(); # Keep remainder } return @cls; } # Convert an array to a BigInt. sub array_to_bint { my @cls = @_; my $out = Math::BigInt->new(0); my $i = 0; while ( @_ ) { my $lsc = Math::BigInt->new( pop @_ ); # LSC $lsc->blsft($bits * $i); # Shift up $out->bior($lsc); # OR to LSC ++$i; } return $out; } sub demo_array_bint { print "\n\nDemo of bint/array conversion... \n"; my $bint_1 = new Math::BigInt($_[0]); print "\tINPUT DECIMAL = ", $bint_1->bstr(), "\n"; my @array = bint_to_array($bint_1); print "\tTHRUPUT ARRAY = ", join ', ', @array, "\n"; my $bint_2 = array_to_bint(@array); print "\tOUTPUT DECIMAL = ", $bint_2->bstr(), "\n"; } demo_array_bint('1234567890' x 6);

Output looks like this on NetBSD 2.0 using Perl 5.8.6.

baal: {39} perl foo.pl Demo of bint/array conversion... INPUT DECIMAL = 123456789012345678901234567890123456789012345 +678901234567890 THRUPUT ARRAY = 19, 2868184292, 3156107799, 1065854007, 23524 +60956, 2362438038, 3460238034, OUTPUT DECIMAL = 123456789012345678901234567890123456789012345 +678901234567890 baal: {40}