سؤال

I'm writing a program that exchanges the values of the bits on positions 3, 4 and 5 with bits on positions 24, 25 and 26 of a given 32-bit unsigned integer.

So lets say I use the number 15 and I want to turn the 4th bit into a 0, I'd use...

int number = 15
int newnumber = number & (~(1 << 3));
// output is 7

This makes sense because I'm exchanging the 4th bit from 1 to 0 so 15(1111) becomes 7(0111).

However this wont work the other way round (change a 0 to a 1), Now I know how to achieve exchanging a 0 to a 1 via a different method, but I really want to understand the code in this method.

So why wont it work?

هل كانت مفيدة؟

المحلول

The truth table for x AND y is:

x y  Output
-----------
0 0    0
0 1    0
1 0    0
1 1    1

In other words, the output/result will only be 1 if both inputs are 1, which means that you cannot change a bit from 0 to 1 through a bitwise AND. Use a bitwise OR for that (e.g. int newnumber = number | (1 << 3);)

To summarize:
Use & ~(1 << n) to clear bit n.
Use | (1 << n) to set bit n.

نصائح أخرى

To set the fourth bit to 0, you AND it with ~(1 << 3) which is the negation of 1000, or 0111.

By the same reasoning, you can set it to 1 by ORing with 1000.

To toggle it, XOR with 1000.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top