I'm trying to solve a question. It says,
Initialize a new variable to the value 17512807u.
Assume we number the bits as usual from 0 as least significant (on the right) to 31 (most significant, on the left). Update bits 18 through 21 with the integer value 8 and bits 10 through 14 with value 17 (decimal). Print the resulting value as an eight digit hexadecimal number to show all of the digits.
Here's the code I came up with:
#include <stdio.h>
int main(){
int value = 17512807u;
int L = 21; // starting left position
int R = 18; // starting right position
int mask = (1 << (L - R + 1) - 1) << R;
int newField = (8 << R) & mask; // integer value 8, shifting to right
int newValue = value & (~mask); // remove range of bits
value = newField | newValue; // update range of bits
L = 14;
R = 10;
mask = (1 << (L - R + 1) - 1) << R;
newField = (17 << R) & mask;
newValue = value & (~mask);
value = newField | newValue;
printf("%08x\n", value);
}
The answer I get is 012b7d67
However, I am told this is the incorrect answer. I do not know what the correct answer is.
int mask = ((1 << (L - R + 1)) - 1) << R;
Your expressions to compute mask are incorrect. You changed the parentheses in the second expression but both are incorrect, and do not even compile:
int mask = ((1 << (L - R + 1) - 1) << R;
...
mask = ((1 << (L - R + 1) - 1 << R);
should be written:
mask = ((1UL << (L - R + 1)) - 1) << R;
Looks like what you are asked to do is use the bit fields. For example, given the type
struct bits{
int a:5;
unsigned short b:3;
unsigned char c:2;
bool d:1;
};
The above struct will have 4 members, each of specific bit length.
If you union that struct with an int you get a "dual-view" of the bits. As a list of fields or as a single integer:
union U{
struct bits fields;
int i;
};
Now the code like
U u;
u.i = 0;
u.fields.b = true;
becomes valid and gives you access to either the whole number or individual bit fields.
来源:https://stackoverflow.com/questions/42259429/updating-fields-of-bits-incorrectly