I am writing a function to process an incoming 32-bit buffer, representing changing data when it is compared to an corresponding stored 32-bit buffer. The position of the changing bit represents a number (i.e. a value of 8 means bit 3) that needs to be processed, along with whether the change is 0->1, or 1->0. Here is the current implementation, please help me improve it! Note that this is not the actual code, it has been simplified to be context-neutral.
uint32_t temp = oldBuffer ^ newBuffer;
uint32_t number = 0;
while (temp != 0)
{
if (temp & 0x1)
{
uint32_t bitValue = 0;
if ((newBuffer& (1 << number)) != 0) bitValue = 1;
processNumber(number, bitValue);
}
number++;
temp = temp >> 1;
}
oldBuffer = newBuffer;
Right now it works but I don't like that it has to check each bit by checking bit 1 and shifting through the entire thing. If there was guarantee to be only 1 bit set that wouldn't be too hard to figure out, but that's not the case.
Edit: To Neil, I guess I am hoping to find a way to get the positions of the bits after the XOR in constant time, instead of shifting all the way through the buffer and checking the bits one by one.