in reply to Modifying multiple bits in a byte - bitwise operators
Thank you very much for the replies all. I tested them all out and am still confused about certain things, so I will definitely be doing some major reading/testing this week. I've posted this here just for completeness.
What I did find out is that I can unset all bits at a certain location by doing a negate AND using the total value of the bits I want to unset. For example, if I want to unset bits 4-3:
my $x = 0xFF; # 0x18 == 24, the max value of both bits # 4-3 set printf("%b\n", &= ~0x18); __END__ 11100111
Then, I can re-set those bits by ORing the bit string with any value within the value range of those two bytes:
$x |= 0x14; # 20; __END__ 11110111
Here's my first working sample of real-world code that I've put together. I'm certain it isn't the most concise, efficient or elegant code, but it'll get better as I learn about how all the bitwise operators work. In my case, I'm dealing with a 16-bit wide configuration register that are stored as two bytes, but when working on them, I merge them together so the code more closely represents what the hardware's datasheet specifies as bit locations:
sub queue { my ($self, $q) = @_; if (defined $q){ if (! exists $queue{$q}){ die "queue param requires a binary string.\n"; } $self->{queue} = $queue{$q}; } $self->{queue} = DEFAULT_QUEUE if ! defined $self->{queue}; my $bits = $self->bits; # unset $bits &= ~MAX_QUEUE; # set $bits |= $self->{queue}; my $lsb = $bits & 0xFF; my $msb = $bits >> 8; $self->register($msb, $lsb); return $self->{queue}; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Modifying multiple bits in a byte - bitwise operators
by Marshall (Canon) on Jan 11, 2017 at 01:05 UTC | |
by stevieb (Canon) on Jan 11, 2017 at 14:11 UTC |