0

Let's say you have a binary number, 8 bits long. You don't know what it is.

xxxx xxxx

I want to set bit 4 to 0. How do I do this?

If I knew the values of x, I could go

xxxx xxxx AND xxxx 0xxx

But I don't know the values of x. How can I do this without knowing the values?

Thank You.

SemperCallide
  • 1,950
  • 6
  • 26
  • 42
  • possible duplicate of [How do you set, clear and toggle a single bit in C/C++?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c-c) – Jonathon Reinhart Mar 24 '14 at 22:01

3 Answers3

4
xxxx xxxx AND 1111 0111

The bitwise AND operator here will not "turn on" bits that are "off" on the left; it can only "turn off" bits that are otherwise "on". This will guarantee that bit 4 is "off", regardless of the input.

To elaborate:

1 AND 1 => 1
0 AND 1 => 0
1 AND 0 => 0
0 AND 0 => 0

Thus by setting every bit "on" in the number on the right, you're guaranteeing that those will either "stay on" or "stay off" -- i.e. they won't be changed. But the one that you set to "off" on the right, that one will always be "off", no matter what comes in on the left.

Kromey
  • 1,202
  • 1
  • 10
  • 13
2

I must be overtired. You can AND the operation anyway.

1 and 1 = 1,

1 and 0 = 0

x and 0 = 0

x and 1 = x

Cool.

SemperCallide
  • 1,950
  • 6
  • 26
  • 42
1
AND 1111 0111

The other bits, the ones you want to leave unchanged will not be altered.

Graham Savage
  • 1,129
  • 13
  • 20