0

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);
}
Rbutler93
  • 73
  • 1
  • 11
  • The most significant nibble of int contains the sign bit, are you sure to compare it with y? – simon_xia Jan 23 '15 at 10:46
  • Yes, an example would be 0xABCDEF01 where y = C therefore false because it isn't the msn. While y = A would be true since it is the same as the msn. So essentially I want to compare the 4 bits of y and the 4 bits of the msn to determine if they are the same. Well that's how I believe it should be approached anyways. – Rbutler93 Jan 23 '15 at 10:54

1 Answers1

2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606