flags - How to decode hex into separate bits in Perl? -
a byte stored 2 hex numbers contains set of flags. need extract these flags, 0's , 1's. iterating on entries in file with:
foreach(<>) { @line = split(/ /,$_); $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"; }
run on data file:
796.129 [1f/01] len:7< 02 01 d5 01 8b 0a 8e 796.224 [1f/01] len:7< 02 01 d4 03 09 a9 b8 796.320 [1f/01] len:7< 00 01 d4 03 07 49 5a 796.415 [1f/01] len:7< 00 01 d4 00 11 a0 ee 796.515 [1f/01] len:7< 00 01 d4 00 00 31 4c 796.627 [1f/01] len:7< 02 01 d4 01 89 c1 fd 796.724 [1f/01] len:7< 02 01 d3 03 06 39 fd 796.820 [1f/01] len:7< 08 01 d4 03 08 40 6f 796.915 [1f/01] len:7< 08 01 d5 00 13 3d a4 797.015 [1f/01] len:7< 08 01 d4 00 00 34 04
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 'false' gets stored empty string instead of '0'.
is there neat trick right @ once, or need convert empty strings zeros "manually"?
if want true/false values numeric, need coerce them 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 empty string ''
false value.
on other hand, might inclined write as:
my (@ryg) = map 0 + !!((hex $line[4]) & $_), 0x3, 0x4, 0x5; print join(', ', @ryg), "\n";
in addition, benefit not using plain numbers in program. consider, example, having %flag
structure gives names these constants, , %col
structure gives names columns interested in. using data posted:
use const::fast; const %flag => ( torr => 0x3, tory => 0x4, torg => 0x5, ); const %col => ( # ... tor => 4, ); while (my $line = <data>) { @line = split ' ', $line; %set_flags = map +($_ => 0 + !!((hex $line[$col{tor}]) & $flag{$_})), qw(torr tory torg); print join(', ', @set_flags{qw(torr tory torg)}), "\n"; } __data__ 796.129 [1f/01] len:7< 02 01 d5 01 8b 0a 8e 796.224 [1f/01] len:7< 02 01 d4 03 09 a9 b8 796.320 [1f/01] len:7< 00 01 d4 03 07 49 5a 796.415 [1f/01] len:7< 00 01 d4 00 11 a0 ee 796.515 [1f/01] len:7< 00 01 d4 00 00 31 4c 796.627 [1f/01] len:7< 02 01 d4 01 89 c1 fd 796.724 [1f/01] len:7< 02 01 d3 03 06 39 fd 796.820 [1f/01] len:7< 08 01 d4 03 08 40 6f 796.915 [1f/01] len:7< 08 01 d5 00 13 3d a4 797.015 [1f/01] len:7< 08 01 d4 00 00 34 04
Comments
Post a Comment