Home > Mobile >  How to unpack bytes in "pairwise reversed" order BA DC?
How to unpack bytes in "pairwise reversed" order BA DC?

Time:10-26

I have a binary string where the bytes are reversed in the following way: The file contains e.g the four bytes 0x18 0xb1 0x35 0x41 and should be interpreted as 0xb1 0x18 0x41 0x35 into my perl string or array. That is, every pair of bytes is reversed.

How can I use unpack to unpack this format?

I also wonder if this kind of packing/format is standard, does it have a name? I apologise if I'm using the wrong terms, I'm not used to byte-level manipulation.

CodePudding user response:

So you have "\x18\xb1\x35\x41..." and you want "\xb1\x18\x41\x35..."

$s =~ s/(.)(.)/$2$1/sg;
my $out = $in =~ s/(.)(.)/$2$1/srg;
my $out = pack "n*", unpack "v*", $in;
my $out = pack "C*", unpack "(xCXXCx)*", $in;

... or an array containing 0xb1, 0x18, 0x41, 0x35, ....

my @out = unpack "C*", $in =~ s/(.)(.)/$2$1/srg;
my @out = unpack "C*", pack "n*", unpack "v*", $in;
my @out = map { $_ >> 8, $_ & 0xFF } unpack "v*", $in;
my @out = unpack "(xCXXCx)*", $in;

CodePudding user response:

This worked for me:

unpack( 'SS', $bytes );
  • Related