I am having trouble with bitwise manipulation.
To do: The hex value of the most significant nibble of x equals y (assume 0 <= y <= 15)
Restrictions: may not use equality (==) or inequality (!=) tests, relative comparison operators, division, modulus, and multiplication, conditionals.
Problem: I need to make my function so that when msb = y it returns 1 and if it is not true 0. However, I keep getting zero even when i run it with 0xff. If someone could point me in the right direction that would be great. Thank you.
int sig_nib(int x, int y){
int shifright = x >> 27;
int result = shifright & y;
return (result ^ y);
}
Silly restrictions. Who broke your compiler?
Something like this should do it:
bool sig_nib(int x, int y)
{
const int top4 = (x >> 28) & 0xf;
return !(top4 ^ y);
}
It uses Boolean inversion (!
) to re-interpret the integer result from the bitwise-xor.