2

I have an specific problem to solve in Perl 5 (using minimal external dependencies, if possible compatible with version 5.12), related to decode an array of bytes like this:

my @data = (0x00, 0x00, 0x00, 0x03, 0x84, 0x14, 0x40, 0x32);

and I want to extract a number like this: 15100821554

I try several variations of pack / unpack without success like

say(unpack("Q", pack("C*", @data)));

print 3620916657624449024

The equivalent code in go is something like this

data := []byte{0x00, 0x00, 0x00, 0x03, 0x84, 0x14, 0x40, 0x32}
deciseconds := int64(binary.BigEndian.Uint64(data))

can be executed here: https://play.golang.org/p/I2J45H-sn-H

any ideas?

1

2 Answers 2

5

You were almost there, the following works:

say unpack 'Q', pack 'C*', reverse @data;
#                          ~~~~~~~

It means you need the opposite endianness, which translates to pack in the following way:

unpack 'Q>', pack 'C*', @data;
#        ^
Sign up to request clarification or add additional context in comments.

1 Comment

The Q> solution is more straightforward, more extensible (e.g. you could use it as part of a larger pattern such as Q>*), and it works on more machines (the reverse solution, ironically, doesn't work on big-endian machines).
-1

Desired result can be achieved with following code

use strict;
use warnings;
use feature 'say';

my $num = 0;
my @data = (0x00, 0x00, 0x00, 0x03, 0x84, 0x14, 0x40, 0x32);

$num = ($num<<8) + $_ for @data;

say $num;

Output

15100821554

NOTE: unpack is a correct way to make conversion

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.