0

I have a bit string that is generated based on user input. I also have another bit string that I use to perform bitwise & with the generated bit string. What I would like to know is how to find out how many bits of the generated bit string has changed from the & operation. So let say if I have 10000101 as generated bit string and 00101111 as a second bit string I use for & operation. The output of the process should be 1 since only the first bit of the generate bit string has changed. How do I do that?

user3273345
  • 127
  • 2
  • 9

2 Answers2

2

What you are looking for is bitwise XOR (exclusively OR), or a^b:

   10000101 ^ 00101111 → 10101010

Is is logically equivalent to (~a&b) | (a&~b)

Maljam
  • 6,244
  • 3
  • 17
  • 30
1

You need to XOR the result with the original to identify which bits were changed:

changedBits = (userInput & generatedInput) ^ userInput

Then, you need to calculate the Hamming Weight of the changedBits value:

int hammingWeight(int i) {
     i = i - ((i >>> 1) & 0x55555555);
     i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
     return (((i + (i >>> 4)) & 0x0F0F0F0F) * 0x01010101) >>> 24;
}

int numberOfChangedBits = hammingWeight(changedBits);

Adjust as needed depending on how many bits your inputs are.

Community
  • 1
  • 1
Darth Android
  • 3,437
  • 18
  • 19