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. 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
So you need to check if number is not equal -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. You probably want check starting from the first (most significant)set bit (so the 15
prints 0
but 14
prints 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.