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}; }

In reply to Re: Modifying multiple bits in a byte - bitwise operators by stevieb
in thread Modifying multiple bits in a byte - bitwise operators by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.