Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return 1 if any bits in an integer equal 1 using bit operations in C

I've been thinking about this problem for hours. Here it is:

Write an expression that returns 1 if a given integer "x" has any bits equal to 1. return 0 otherwise.

I understand that I'm essentially just trying to figure out if x == 0 because that is the only int that has no 1 bits, but I can't figure out a solution. You may not use traditional control structures. You may use bitwise operators, addition, subtraction, and bit shifts. Suggestions?

like image 793
jjAman Avatar asked Feb 08 '11 17:02

jjAman


People also ask

How do you check if all even bits are 1?

Determine if all even place bits (counting from left to right) are set to 1. For instance, 0101 0101 would count whereas 1011 1000 would not count. If the the bit has 1's in all even places, return 1, or else return 0.

Which of the following operators is return 1 if the corresponding bits are different?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

Which operator returns 1 if one of the bits have a value of 1 and the other has a value of 0 otherwise it returns a value?

Bitwise not operator: Returns one's complement of the number. Bitwise xor operator: Returns 1 if one of the bits is 1 and the other is 0 else returns false.

Which operator sets the bits in the result to 1?

The Bitwise Operators Similar to the || operator, but on a bit-by-bit basis. Bits in the result set to 1 if at least one of the corresponding bits in the two operands is 1. 0 otherwise. Bits in the result set to 1 if exactly one of the corresponding bits in the two operands is 1.


1 Answers

Here's the best I could come up with:

y = (((-x) | x) >> (BITS - 1)) & 1;

where BITS = 32 for 32 bit ints, i.e. BITS = sizeof(int) * CHAR_BIT;

Here's a test program:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    const int BITS = sizeof(int) * CHAR_BIT;

    if (argc == 2)
    {
        int x = atoi(argv[1]);
        int y = (((-x) | x) >> (BITS - 1)) & 1;

        printf("%d -> %d\n", x, y);
    }

    return 0;
}
like image 185
Paul R Avatar answered Oct 14 '22 20:10

Paul R