3

Update: Salva correctly points out that I was wrong about the introduction of the "Q" pack template. It's the ">" modifier that doesn't go back to 5.8.

Perl 5.10 introduced the pack() modifier ">", which, for my use case with "Q" packs an unsigned quad (64bit) value in big endian.

Now, I'm looking for an efficient equivalent for

pack("Q>2", @ints)

where @ints contains two 64bit unsigned ints. "Q>2" means "pack two unsigned quads in big-endian byte order". Obviously, I want this because I am (at least temporarily) tied to a pre-5.10 Perl.

Update2: Actually, on further reflection, something as simple as the following should do:

pack("N4", $ints[0] >> 32, $ints[0], $ints[1] >> 32, $ints[1])

Appears to work on my 64bit x86-64 Linux. Any reason why this might not be exactly the same as pack("Q>2", @ints)? Any platform-specific matters?

What's the reverse (ie. equivalent to unpack("Q>2", @ints))?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
tsee
  • 5,034
  • 1
  • 19
  • 27

1 Answers1

5

The Q pattern was introduced in perl 5.6. Your real problem may be that you are trying to use it in a perl compiled without 64bit support.

Anyway, you can use Math::Int64.

Update, an example:

use Math::Int64 qw(int64_to_native);
my $packed = join '', map int64_to_native($_), @ints;

Another option, if you are on a 64bit perl supporting Q but not Q>, is to reorder the bytes yourself:

pack 'C*', reverse unpack 'C*', pack 'Q', $int;
salva
  • 9,943
  • 4
  • 29
  • 57
  • Thank you for finding out that I totally misremembered the portability issue: It's ">" that doesn't go back, so the closest thing that enforces big-endian order is the "N" template, which is 32bit/unsigned only. So in spirit, my question stands, but your (previously very valid) answer doesn't quite apply any more. Sorry for that, my bad. PS: This is a 64bit perl. – tsee Mar 15 '12 at 09:21
  • 2
    Here's what I came up with as the reverse of the pack: `my @tmp = unpack("N4", $out2); my @orig= ( ($tmp[0] << 32) | $tmp[1], ($tmp[2] << 32) | $tmp[3] );` – tsee Mar 15 '12 at 09:51