← All problems · Bit Manipulation
Count Changed Register Bits
Return how many bit positions differ between two register snapshots.
Implement unsigned changed(uint32_t a, uint32_t b).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
XOR marks changed bits.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
unsigned changed(uint32_t a, uint32_t b)
{
uint32_t x=a^b; unsigned n=0; while(x){x &= x-1; ++n;} return n;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
unsigned changed(std::uint32_t a, std::uint32_t b)
{
std::uint32_t x=a^b; unsigned n=0; while(x){x &= x-1; ++n;} return n;
}
Each iteration removes one differing bit.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(changed(0,0)==0);
CHECK(changed(0,UINT32_MAX)==32);
CHECK(changed(8,7)==4);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}