pack, unpack and 64-bit values

B

Bill

According to the perlfunc perl docs, the 'Q' in format string allows
64-bit entities to be used in pack and unpack:

my $binary = pack 'Q', $big_number;


my @int64 = unpack 'Q*', $buffer;



Two questions:

1. Is the 'Q' network order, or machine order in its bytes?

2. Can anyone show an efficient code snippet to emulate the above in
32-bit perl versions that may not support 64-bit pack and unpack?
 
B

Big and Blue

Bill said:
According to the perlfunc perl docs, the 'Q' in format string allows
64-bit entities to be used in pack and unpack:

1. Is the 'Q' network order, or machine order in its bytes?

It will be in machine order. Network order only applies to 16- and 32-
bit quantities, as in the ntohl and ntohs macros, as network code doesn't
use 64-bit ones
 
W

William Herrera

Big said:
It will be in machine order. Network order only applies to 16- and
32- bit quantities, as in the ntohl and ntohs macros, as network code
doesn't use 64-bit ones

I was afraid of that. So I guess to be network portable you must process
pack and unpack of integer binary values as 32-bit chunks tops.
 
B

Bart Lateur

William said:
I was afraid of that. So I guess to be network portable you must process
pack and unpack of integer binary values as 32-bit chunks tops.

Not necessarily... though it would be the most portable solution, as
most platforms don't support "Q".

You could test the machine's endianness, stuff it into a constant, and
simply reverse the 8 byte packed string before unpacking it with "Q".

use constant LITTLE_ENDIAN => unpack "C", pack "s", 1;
my $s = pack "C*", 0 .. 7;
my $int = unpack "Q", LITTLE_ENDIAN ? $s : reverse $s;

Testing this with B::Deparse, using "perl -MO=Deparse test.pl" produces
the following output on 5.6.1/Win32:

sub LITTLE_ENDIAN () {
package constant;
$scalar;
}
my $s = pack('C*', (0, 1, 2, 3, 4, 5, 6, 7));
my $int = unpack('Q', $s);

test.pl syntax OK

So it gets resolved at compile time: there's no runtime penalty.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top