4zap 4zap - 1 year ago 66
Perl Question

Perl - byte swaping after reading the probe values

i need help in Perl. Maybe for you an easy question to answer...
From from AD Converter i get values like 0X43b7 on an debian wheezy.
I read this values with the i2cget command

$EC = `sudo i2cget -y 1 0x4a 0x00 w` ;

what i get is an hex value 0x34c2. The used microcontroller did somethink like an little endian to this value and i need the swap the higher value bytes against the lower value bytes. I get an hint, but in python ... i had no glue how to handle this. Is there an easy expression in Perl for this Python line`?

assert line.startswith("0x")
word = int(line[2:], 16)
yield struct.unpack(">H", struct.pack("<H", word))[0]

I never swaped bytes in Perl and not realy shure how to translate this.

Answer Source

If the input is the string 0x34c2 and you want to get the bytes 43 2c (or the string "432c") back, you can use

my $EC = "0x34c2";
my $output = pack 'h4', substr $EC, 2;  # --> \x43\x2c
my $string = unpack 'H4', $output;      # --> "432c"

If you just want to swap the "bytes" in a string, you can use substitution

my $EC = "0x34c2";
(my $output = $EC) =~ s/(..)(..)$/$2$1/;

or substr:

my $EC = "0x34c2";
my $output = $EC;
substr $output, 4, 0, substr $output, 2, 2, q();