I have a problem understanding and using the ‘vec’ keyword.
I am reading a logpacket in which values are stored in little endian hexadecimal. In my code, I have to unpack the different bytes into scalars using the unpack keyword.
Here’s an example of my problem:
my @hexData1 = qw(50 65);
my $data = pack ('C*', @hexData1);
my $x = unpack("H4",$data); # At which point the hexadecimal number became a number
print $x."\n";
#my $foo = sprintf("%x", $foo);
print "$_-> " . vec("\x65\x50", $_, 1) . ", " for (0..15); # This works.
print "\n";
But I want to use the above statement in the way below. I don’t want to send a string of hexadecimal in quotes. I want to use the scalar array of hex $x. But it won’t work. How do I convert my $x to a hexadecimal string. This is my requirement.
print "$_-> " . vec($x, $_, 1).", " for (0..15); # This doesn't work.
print "\n";
My final objective is to read the third bit from the right of the two byte hexadecimal number.
How do I use the ‘vec’ command for that?
You are making the mistake of
unpacking $data into$xbefore using it in a call tovec.vecexpects a string, so if you supply a number it will be converted to a string before being used. Here’s your codeThe
Cpackformat uses each value in the source list as a character code. It is the same as callingchron each value and concatenating them. Unfortunately your values look like decimal, so you are gettingchr(50).chr(65)or"2A". Since your values are little-endian, what you want ischr(0x65).chr(0x50)or"\x65\x50", so you must writewhich reverses the list of data (to account for it being little-endian) and packs it as if it was a list of two-digit hex strings (which, fortunately, it is).
Now you have done enough. As I say,
vecexpects a string so you can writeand it will show you the bits you expect. To extract the the 3rd bit from the right (assuming you mean bit 13, where the last bit is bit 15) you want