不正确地更新位字段
我正试图解决一个问题。 它说,
将新变量初始化为值17512807u。
假设我们像往常一样将这些位从0表示为最不重要(在右侧)到31(最重要的,在左侧)。 使用整数值8和位10到14更新位18到21,值为17(十进制)。 将结果值打印为八位hex数字以显示所有数字。
这是我提出的代码:
#include 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); }
我得到的答案是012b7d67
但是,我被告知这是错误的答案。 我不知道答案是什么。
int mask = ((1 << (L - R + 1)) - 1) << R;
您计算mask
表达式不正确。 您更改了第二个表达式中的括号,但两者都不正确,甚至不编译:
int mask = ((1 << (L - R + 1) - 1) << R; ... mask = ((1 << (L - R + 1) - 1 << R);
应该写:
mask = ((1UL << (L - R + 1)) - 1) << R;
看起来你被要求做的是使用位字段。 例如,给定类型
struct bits{ int a:5; unsigned short b:3; unsigned char c:2; bool d:1; };
上面的struct
将有4个成员,每个成员具有特定的位长。
如果你将这个结构与int
你会得到这些位的“双视图”。 作为字段列表或作为单个整数:
union U{ struct bits fields; int i; };
现在的代码就像
U u; ui = 0; u.fields.b = true;
变为有效,并允许您访问整数或单个位字段。