Zach Smith
Zach Smith

Reputation: 5674

Clarification on Masking Bits

I have a quick question about masking bits. If I want to turn two 8 bit streams on, do I

use the AND logic against the two:

     10101010
AND  01101001
     ________
     00101000

or do I actually change one of the bits in the stream to turn the bits on? I guess my question is when I'm turning on (using AND) or turning off (using OR) do I actually change any of the bits, or just comparing the two using the AND/OR logic?

Upvotes: 1

Views: 182

Answers (3)

Gustavo Mori
Gustavo Mori

Reputation: 8386

To turn ON (1), you would use the OR operator with a 1 in the position you want to turn ON, because no matter what the original value in the stream is, the result would be ON

   00000000 // whatever the values in the input
OR 00000001 // 'OR' turns on the last position in the stream
   --------- 
   00000001

To turn OFF (0), you would use the AND operator with a 0 in the position you want to turn OFF, because no matter what the original value in the input stream, the result would be OFF.

    11111111 // whatever the values here
AND 11111110 // turns off the last position in the stream
    ---------
    11111110

Upvotes: 1

Charles E. Grant
Charles E. Grant

Reputation: 6021

I'm not sure what you mean by 'streams' in this case.

In most languages you are going to have to have an assignment as well as the binary operation.

That is you would typically have something like

foo = get_byte() // Call some function to get the original value of foo
foo = foo AND 11110111 // Replace foo with the result of the AND, which
                       // in this case will turn off the 4th bit, and leave
                       // the other bits unchanged

The last line replaces the contents of foo with the results of the binary operation

Upvotes: 0

Zach Smith
Zach Smith

Reputation: 5674

Others, correct me if I am wrong:

To turn ON the 4th bit in an 8bit stream you would compare the 8bit stream using the OR logic using 00001000.

To turn OFF the 4th bith in an 8bit stream you would compare the 8bit stream using the AND logic using 11110111.

To toggle the bit you would use 11111111 using the XOR logic.

Upvotes: 0

Related Questions