Reputation: 127
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?
Upvotes: 0
Views: 900
Reputation: 3502
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.
Upvotes: 1
Reputation: 6284
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)
Upvotes: 2