Updating fields of bits incorrectly

坚强是说给别人听的谎言 提交于 2019-12-02 01:35:51
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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!