Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: pack 64 bit int ?

by jsprat (Curate)
on Apr 30, 2002 at 17:52 UTC ( #163137=note: print w/replies, xml ) Need Help??

in reply to pack 64 bit int ?

I'd use left and right shift. I don't know how this would benchmark (and I don't have the time or energy to try ;) against your version, but this looks cleaner, at least to me.

sub pack64bit { my $i = new Math::BigInt shift(); my $j = new Math::BigInt $i->brsft(32); my $k = $i - $j->blsft(32); return pack('NN', $j, $k); }

Mine (as well as yours) will break if something unexpected is passed.

Update:Anonymous Monk, otherwise known as frankied noticed that this breaks for negative numbers.

Something bothered me anyway about using Math::BigInt to manipulate bits, so I did a rewrite using Bit::Vector:

sub pack_bv{ use Bit::Vector; my $vec = Bit::Vector->new_Dec(64, shift); return pack 'NN', $vec->Chunk_Read(32, 32), $vec->Chunk_Read(32, 0); }

This one looks even cleaner - and better yet, it works!

Replies are listed 'Best First'.
Re: Re: pack 64 bit int ?
by Anonymous Monk on Apr 30, 2002 at 18:18 UTC
    that won't work for negative numbers (which is why I use that ugly if($i<0){} in my attempt). BigInt (perhaps unfortunately) doesn't seem to use 2's complement.

    (eg. -1 results in 00000000ffffffff instead of ffffffffffffffff)

      (mental note to login before submitting)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://163137]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2021-03-07 12:09 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (121 votes). Check out past polls.