So, I've finally gotten around to working with bitwise operators, and I'm a bit stuck.
What I want to do is have a pre-configured byte, then reconfigure specific bits within it depending on a parameter to a function. Say I have a byte set to 128 (10000000), and want to flip the last two bits. That's easy with an OR, as the least significant bits are already 0.
However, say a function receives a parameter that says to change that 3 (last two bits) to a two instead (unset the right-most bit to 0). I can easily do that as well:
use warnings; use strict; my $base = 128; # OR to get 131 (10000011) $base = $base | 3; # combine NOT and AND and unset the last bit $base = $base &= ~(1 << 1);
What I'm wondering is if there's a way to change several bits at a time. Instead of the last bit, what if I wanted to go from 10001010 to say, 10001101? (from 10 to 13 in the last four bits). Is there an easy way to do that, or does each bit have to be switched one at a time?
I suppose I could just subtract the initial number then add in the new value, but that kind of defeats the purpose of me learning this. Am I thinking about this all wrong?
In reply to Modifying multiple bits in a byte - bitwise operators by stevieb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |