SF. SF. - 16 days ago 5
Perl Question

How to decode hex into separate bits in Perl?

A byte stored as two hex numbers contains a set of flags. I need to extract these flags, as 0's and 1's. Iterating over entries in a file with:

$torR = !!((hex $line[4]) & 0x3); # bit 0 or 1
$torY = !!((hex $line[4]) & 0x4); # bit 2
$torG = !!((hex $line[4]) & 0x8); # bit 3

print "$torR,$torY,$torG\n";


Actual Result -

1,,
1,,
,,
,,
,,
1,,
1,,
,,1
,,1
,,1


Desired result:

1,0,0
1,0,0
0,0,0
0,0,0
0,0,0
1,0,0
1,0,0
0,0,1
0,0,1
0,0,1


Seems like 'false' gets stored as empty string instead of '0'.

Is there a neat trick to get this right at once, or do I need to convert empty strings to zeros "manually"?

Answer

If you want the true/false values to be numeric, you need to coerce them to be numeric:

$torR = 0 + !!((hex $line[4]) & 0x3);  # bit 0 or 1
$torY = 0 + !!((hex $line[4]) & 0x4);  # bit 2
$torG = 0 + !!((hex $line[4]) & 0x8);  # bit 3

Keep in mind that the empty string '' is also a false value.

On the other hand, I might be inclined to write that as:

my (@ryg) = map 0 + !!((hex $line[4]) & $_), 0x3, 0x4, 0x5;
print join(', ', @ryg), "\n";
Comments