Hi Ken, it's not broken code, just sub-optimum technique. Bitwise operators are fundamental to most processors so they are generally very efficient at a processor level. In particular there should be no need for a test and conditional set (using xor or otherwise). There is a short comming with the code presented so far though. In the OP's context of setting flags in a bit set it's fine, but a common requirement is to update the value of a field of bits (1 to many adjacent bits). Again there is no need for a test. You just:
use strict;
use warnings;
my $fieldIndex = 3;
my $fieldMask = 0b111 << $fieldIndex;
for my $fieldValue (0b000, 0b001, 0b100, 0b111) {
my $fieldBits = $fieldMask & ($fieldValue << $fieldIndex);
printf "With field value 0b%08b: \n ", $fieldBits;
for my $pattern (0x00, 0xff) {
my $value = ($pattern & ~$fieldMask) | $fieldBits;
printf "0b%08b --> 0b%08b ", $pattern, $value;
}
print "\n";
}
Prints:
With field value 0b00000000:
0b00000000 --> 0b00000000 0b11111111 --> 0b11000111
With field value 0b00001000:
0b00000000 --> 0b00001000 0b11111111 --> 0b11001111
With field value 0b00100000:
0b00000000 --> 0b00100000 0b11111111 --> 0b11100111
With field value 0b00111000:
0b00000000 --> 0b00111000 0b11111111 --> 0b11111111
In this case the field is three bits wide (see $fieldMask). The important lines are the generation of $fieldBits which gets the field value in the right place and the generation of $value which inserts the field bits into the target bit pattern. This is bread and butter stuff in the embedded world, and is common when twiddling bit for things like network packets or in binary files.
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
|