Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   pack, unpack and 64-bit values (http://www.velocityreviews.com/forums/t896521-pack-unpack-and-64-bit-values.html)

Bill 02-09-2006 05:55 PM

pack, unpack and 64-bit values
 
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?


Big and Blue 02-09-2006 11:41 PM

Re: pack, unpack and 64-bit values
 
Bill wrote:

> 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

--
Just because I've written it doesn't mean that
either you or I have to believe it.

William Herrera 02-10-2006 05:01 AM

Re: pack, unpack and 64-bit values
 
Big and Blue wrote:
> Bill wrote:
>
>> 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
>


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.

Bart Lateur 02-10-2006 08:54 AM

Re: pack, unpack and 64-bit values
 
William Herrera wrote:

>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.

--
Bart.


All times are GMT. The time now is 01:17 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.