32 Bit Integer Mask

瘦欲@ 提交于 2020-01-05 02:31:16

问题


I'm finishing up some CSE homework and I have a quick question about declaring integers of larger bit sizes. My task is to implement a function that returns 1 if any odd bit of x is 1 (assuming size of x is 32 bits) and returns 0 otherwise.

Am I allowed to declare an integer with the bit value:

10101010101010101010101010101010

If so, are there any problems that could arise from this? If not, why not?? What alternatives do I have?

My function:

int any_odd_one(unsigned x)
{
    int mask = 10101010101010101010101010101010
    if(x & mask)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

Thanks in advance for any assistance!

-Matt


回答1:


You can't use binary literals in C. Instead, use hexadecimal or octal notation.

In your case, you'd use unsigned mask = 0xaaaaaaaa since 10101010... is 0xaaaaaaaa when expressed in hexadecimal (each 1010 is a in hex).




回答2:


It is more fun to implement this as return !!(x&-1u/3*2);.

In addition to the integer width stated in the problem, it works for any even number of bits in the unsigned type.



来源:https://stackoverflow.com/questions/13095354/32-bit-integer-mask

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