[英]How to print 1 when any bit of a number equals 0?
I need to print out the value 1 when any bit of a number equals 0, and am currently struggling with how I would go about doing this.当数字的任何位等于 0 时,我需要打印出值 1,并且目前正在苦苦思索如何进行此操作。 I am not supposed to use any equality or inequality tests, and am basically restricted to just bit-level and logic operations.
我不应该使用任何相等或不等测试,并且基本上仅限于位级和逻辑运算。 Any ideas?
有任何想法吗?
int b = 15;
printf("prints 1 when any bit of a number equals 0: %d\n", //PRINT GOES HERE);
b = 10;
printf("prints 1 when any bit of a number equals 0: %d\n", //PRINT GOES HERE);
I do not understand your question but for two complement signed integer all bits are set for number -1
我不明白你的问题,但对于两个补码有符号整数,所有位都设置为数字
-1
So you need to check if number is not equal -1
所以你需要检查数字是否不等于
-1
void foo(int a)
{
printf("prints 1 when any bit of a number equals 0: %d\n", !((unsigned)a ^ (unsigned)-1));
}
int main(void)
{
foo(15);
}
But IMO it is too trivial.但 IMO 这太微不足道了。 You probably want check starting from the first (most significant)set bit (so the
15
prints 0
but 14
prints 1
):您可能希望从第一个(最重要的)设置位开始检查(因此
15
打印0
但14
打印1
):
unsigned mask(int a)
{
int bit;
if(!((unsigned)a ^ (unsigned)-1)) return -1;
for(bit = sizeof(a)*CHAR_BIT - 1; bit; bit--)
{
if(((unsigned)a & (1U << bit))) break;
}
return (1U << (bit + 1)) - 1;
}
void foo(int a)
{
printf("prints 1 when any bit of a number equals 0: %d\n", !!((a & mask(a)) ^ mask(a)));
}
int main(void)
{
foo(15);
}
You would want to create a mask with all 1's (~0x0) then XOR it with the number.您可能想要创建一个全为 1 (~0x0) 的掩码,然后将其与数字进行异或。 If there are any 1's afterwords then at least one of the original bits was 0, and thus you can use &&1 to return 1 if there is at least one 1 and 0 if not.
如果有任何 1 的后记,那么至少有一个原始位是 0,因此如果至少有一个 1,您可以使用 &&1 返回 1,否则返回 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.