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

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.