stevieb has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Modifying multiple bits in a byte - bitwise operators
by BrowserUk (Patriarch) on Jan 10, 2017 at 00:46 UTC | |
|
Re: Modifying multiple bits in a byte - bitwise operators (xor)
by Anonymous Monk on Jan 10, 2017 at 00:50 UTC | |
|
Re: Modifying multiple bits in a byte - bitwise operators
by AnomalousMonk (Archbishop) on Jan 10, 2017 at 00:50 UTC | |
|
Re: Modifying multiple bits in a byte - bitwise operators
by johngg (Canon) on Jan 10, 2017 at 16:43 UTC | |
|
Re: Modifying multiple bits in a byte - bitwise operators
by Lotus1 (Vicar) on Jan 10, 2017 at 20:52 UTC | |
|
Re: Modifying multiple bits in a byte - bitwise operators
by stevieb (Canon) on Jan 10, 2017 at 17:01 UTC | |
by Marshall (Canon) on Jan 11, 2017 at 01:05 UTC | |
by stevieb (Canon) on Jan 11, 2017 at 14:11 UTC |