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?
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With