Reputation:
My assignment is to write one or more C statements that clears (i.e. sets to 0) bits 11 and 12 of the variable "x" without disturbing the other bits using bit-level C-operators. My professor says: "The variable "mask", declared below, may be helpful."
int mask = 0x00001800;
int x = arbitrary_value;
Should I be using shift operations combined with bit-level operations? I'm a bit unclear how to make this happen.
Upvotes: 2
Views: 603
Reputation:
Grab a paper or open the editor of your choice, and re-write the mask's hex notation in binary.
Noticed which bits are set?
Now you need to combine some Boolean operations to actually clear these bits in x. Hint: You need 2 of the basic operations detailled here:
https://en.wikipedia.org/wiki/Boolean_algebra#Operations
Be careful to ensure, that each possible input is covered, i.e.:
00 -> 00
01 -> 00
10 -> 00
11 -> 00
Upvotes: 1
Reputation: 182
@Garrett, To force or mask some values you will use the bitwise operands (&, |, ~, ^). How to do it is up to you. You can create a mask, like that one you created 0x00001800. If you convert this mask to binary you get this: 1100000000000. As you can see starting from the right the bits 11 and 12 are the only ones that stay high.
Now, to use this mask to mask a value you need to know what you want to do. For your case you want to force bits 11 and 12 of another variable to 0, so, to force something to 0 you can use the AND bitwise operand (&) passing 0 where you want to force 0 and 1 where you want to stay exactly how it is on the other variable. If you want to use the mask 0x1800 for this operation you must first invert all his bits, because you want 0s right where this mask has 1s and 1s right where it has 0s. To invert all the bits you can use NOT bitwise operand, like:
int mask = 0x1800;
int invertedMask = ~mask;
Value of variables in binary:
mask = 1100000000000 invertedMask = 0011111111111
Now you can force the bits 11 and 12 from a variable to zero, for example:
int mask = 0x1800; //Value in binary 1100000000000
int value = 7347; //Value in binary 1110010110011
int finalValue = 0;
mask = ~mask; // Now mask value is 0011111111111
finalValue = value&mask; //final value is 0010010110011
As you can see, bits 11 and 12 (from right to left) were forced down while other stay right as in value variable.
And using this principles you can use a lot of other combination, including shift of bits to deslocate the bits of your mask for example.
Upvotes: 2