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

Two points:
  1. A tiny change should save you big time. Instead of doing the exponential stuff of 256 every time, you should use a variable to store the current value of 256 ** k from each iteration, and next iteration just multiply it by 256, to get 256 ** (k + 1), see the code.

    Now the complexity is a linear function of your array size, ~ o(n).

  2. After my code change, you don't need a $count any more, but I still want to mention that there is absolutely no need to use BigInt for $count, that's really really huge, is your number that HUGE?
Be careful, pack and unpack does not fit in the picture.
sub bytearray_to_bigint { my @array = @_; my $base = Math::BigInt->new('1'); my $result = Math::BigInt->new('0'); foreach my $a (@array) { $result += $a * $base; $base *= 256; } return $result; }
  • Comment on Re: Converting an array of bytes into a BigInt - speed considerations
  • Download Code