Ergometer has asked for the wisdom of the Perl Monks concerning the following question:

Greetings monks, I'm trying to convert an unsigned long integer to a binary string of numbers. After searching through past posts I found that the following code should wor:

$bits= unpack( "b64", pack( "Q", 4294967295)):

However this only works up to 2^(32)-1 and treats every number greater as 32 1's and the rest zeroes. This made me think I had 32 bit perl but I read I wouldn't be able to use Quad if I did. Any ideas as to what I am doing wrong or if there is another way to accomplish this. I have not had luck with sprintf either due to the same issue. (Not creating numbers greater than 2^(32)-1) Thanks for any help

Replies are listed 'Best First'.
Re: Convert unsigned long int (64bit) to binary string(64bits)
by hdb (Monsignor) on Dec 13, 2013 at 07:21 UTC

    Do you get any hints for 64bits when you run perl -V? I am using Strawberry 5.16.3 64bit on Win7 and I get the following:

    print unpack( "b64", pack( "Q", 4_294_967_295)), "\n"; print unpack( "b64", pack( "Q", 126_294_967_295)), "\n"; Result: 1111111111111111111111111111111100000000000000000000000000000000 1111111111000010001000111110011010111000000000000000000000000000
      It also works right for me on Ubuntu i386 which has Perl compiled with 64bit integers.

      I ran perl -V | grep use64 and I got use64bitint=define, use64bitall=define,uselongdouble=undef. It seems to be running perfectly this morning though and I can't replicate the weird results I saw last night. Thanks for the help anyways.

Re: Convert unsigned long int (64bit) to binary string(64bits)
by taint (Chaplain) on Dec 13, 2013 at 07:39 UTC
    I get the same results as hdb.

    My Perl is 64bit, and I'm on a *BSD box -- pertinent bits from perl -V: use64bitint=define, use64bitall=define USE_64_BIT_ALL

    print unpack( "b64", pack( "Q", 4_294_967_295)), "\n"; print unpack( "b64", pack( "Q", 126_294_967_295)), "\n"; print unpack( "b64", pack( "Q", 4294967295)), "\n"; 1111111111111111111111111111111100000000000000000000000000000000 1111111111000010001000111110011010111000000000000000000000000000 1111111111111111111111111111111100000000000000000000000000000000

    --Chris

    EDIT: I might add, it's a 6core AMD CPU (AM2 I think)
    Yes. What say about me, is true.
    
Re: Convert unsigned long int (64bit) to binary string(64bits) (endianness? Convert::Binary::C)
by Anonymous Monk on Dec 13, 2013 at 07:50 UTC
    What endianess? I would go straight for Convert::Binary::C

    But, does this look like something you want?

    $ perl -le " print unpack q/ b64 /, pack q/a8/, 4294967295 " 0010110001001100100111000010110010011100011011001110110001001100 $ perl -le " print unpack q/ b64 /, 4294967295 " 0010110001001100100111000010110010011100011011001110110001001100 use constant CAN_PACK_QUADS => !! eval { my $f = pack 'q'; 1 }; sub UInt64 { unpack( ( CAN_PACK_QUADS ? 'Q<' : 'a8' ), $_[-1] ) }