[Israel.pm] packing and unpacking large numbers

Shmuel Fomberg semuelf at 012.net.il
Sun Jul 29 12:44:22 PDT 2007


Yona Shlomo Said:

>> You can always take the stringy path, that is: (tested)
>> $x = Math::BigInt->new('123456789123');
>> $str = $x->as_bin();
>> substr($str, 0, 2) = '0' x (64 - length($str) + 2);
>> $binary = pack "B*", $str;
>>
>> just make sure that you have the right byte order.
>> (big/little indeans and so)
>
>Can you explain the operations?
>
>I looks like you're padding with '0' characters the binary
>representation in string format of the big number -- but I
>don't understand the purpose of the
>    substr($str, 0, 2) = '0' x (64 - length($str) + 2);
>neither the lvalue nor the rvalue

Well, the as_bin() method returns the string with a '0b' prefix. The
lvalue propose it to eliminate it. 
The rvalue is, like you said, for padding the number with '0'. Pack "B*"
create one byte for every 8 binary characters. So I need 64 characters
for it to produce 8 byte number.

Shmuel.





More information about the Perl mailing list