given an integer variable a, write two code fragments. The first should set bit 3 of a.
The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified.
某gpt回答
To set bit 3 of integer variable a:
a = a | (1 << 3);
To clear bit 3 of integer variable a:
a = a & ~(1 << 3);
Explanation:
In the first code fragment, we use the bitwise OR operator |
to set bit 3 of a. We do this by left-shifting the number 1 by 3 bits to create a mask with a 1 in the 3rd bit position (i.e., 00001000 in binary). We then use the OR operator to combine this mask with the original value of a, which will set the 3rd bit to 1 if it was previously 0, and leave it unchanged if it was already 1.
In the second code fragment, we use the bitwise AND operator &
to clear bit 3 of a. We do this by creating a mask with a 0 in the 3rd bit position and 1s in all other positions (i.e., 11110111 in binary) by taking the complement of the mask we used in the first code fragment. We then use the AND operator to combine this mask with the original value of a, which will clear the 3rd bit to 0 if it was previously 1, and leave it unchanged if it was already 0.