Question

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.

Was it helpful?

Solution 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.

OTHER TIPS

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.

AND 1111 0111

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top