Can someone please help me out with a solution? I need to compare two int values to each other and return the most significant bit position in which they differ. Duplicate values will not be allowed.
For example, if comparing 16 and 4:
16 = 10000
4 = 00100
This should return a value of 4 since they differ in the 4th bit. Likewise, if comparing 7 and 6
7 = 111
6 = 110
This should return a value of 0.
I'm fairly certain this can be done using XOR somehow, but I'm pretty weak with bitwise operations. Could someone please help me out? Thanks.
Thanks for the help. Here's what I ended up doing, and it seems to be working:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int compare_bits(unsignedint val1, unsignedint val2)
{
for (int i = NUM_BITS; i >= 0; i--)
{
if (get_bit(val1, i) ^ get_bit(val2, i)) // if the bit values are different, return the MSB position
{
return i;
}
}
}
bool get_bit(unsignedint val, int position)
{
return (val & (1 << position)) >> position;
}