 This is just a general question about bits. We were given an example value of 10000010 and we were to toggle 1 and 7 placements of 10000010 to find its mask. Why the mask have the same value as the given value? If I understood XOR and determining its mask, I thought that we’d toggle 1 to 0 and 0 to 1? Shouldn’t be the two 1’s in this case be zeros instead? I hope someone can explain XOR and masking for me. Thank you in advance.

I could be slightly off here, but…

A “mask” is just a sequence of bits that can be applied, in conjunction with a given bitwise operation, to toggle some or all of the bits in the target sequence.

If we consider your starting byte:

``````10000010
``````

If I’m understanding your question correctly, you’ve been asked to compute the necessary mask to toggle bits `1` and `7` using XOR.

The truth table for the XOR operation looks like this:

`````` A | B | XOR
-------------
0 | 0 |  0
1 | 0 |  1
0 | 1 |  1
1 | 1 |  0
``````

`XOR` - exclusive or - will return a “true” value (`1`) only in circumstances where only one bit is “true” (equal to one). If both bits have the same value, then `XOR` returns a “false” value (`0`). (This is different to `OR`, where you will get a “true” value for any two bit combinations other than `0 OR 0`.)

Hopefully, with this explanation of how `XOR` works, you can now see why the mask to toggle only bits `1` and `7` is identical to the original value. Here’s the truth table again:

``````POS | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
------------------------------------
A | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0
------------------------------------
B | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0
------------------------------------
XOR | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
``````

Does that help at all?

3 Likes