Bitwise Comparison

Apr 2, 2012 at 4:59am
Hello,

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.


Apr 2, 2012 at 5:24am
You'll need the bitshift right operator (>>) and the remainder operator (%), and a counter.

Good luck!
Apr 2, 2012 at 5:39am
XOR will give 1 if the bits differ.
To find out the MSB set, just rotate to the right till the number becomes 0
Apr 2, 2012 at 5:39am
you could do what Duas said..

are you storing these values in an array? if so this is the method i would use:

1) get bit size length 5 for the first one, 3 for the second example
2)
1
2
3
4
5
6
for(int i = 0; i < bitsize; i++)
    {
          if( mybit1[i] == mybit2[i];
          mysigbit = i;
          else //some error for all bits the same
     }
Apr 2, 2012 at 7:37am
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(unsigned int val1, unsigned int 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(unsigned int val, int position)
{
    return (val & (1 << position)) >> position; 
}

Apr 2, 2012 at 7:45am
the bitwise OR operator in C++ is "|" (without quotation marks)

and the bitwise AND operator in C++ is "&" (also without quotation marks)

and NOT is ~

You can use the standard form of XOR: A'B + AB' with those operators.
Apr 2, 2012 at 6:32pm
Or you could just use the standard bitwise XOR operator "^".
Topic archived. No new replies allowed.