I am writing a small C program to count the number of bits which need to be flipped to make one number equal to another.
The program works very fine but i observe abnormal behaviour (Program hangs) when i pass ULONG_MAX as an argument. Why is this happening? See code below
#include <stdio.h>
#include <limits.h>
#include <stddef.h>
/**
* flip_bits - Count the number of bits to flip to equalize two numbers
* @n: First number
* @m: Second number
*
* Return: the number of bits to flip
*/
unsigned int flip_bits(unsigned long int n, unsigned long int m)
{
unsigned long int diff, count;
int i;
diff = n ^ m;
count = 0;
i = 0;
while (diff >> i)
{
if (diff >> i & 1)
count++;
i++;
}
return (count);
}
/**
* main - check the code
*
* Return: Always 0.
*/
int main(void)
{
unsigned int n;
n = flip_bits(1024, 1);
printf("%u\n", n);
n = flip_bits(402, 98);
printf("%u\n", n);
n = flip_bits(1024, 3);
printf("%u\n", n);
n = flip_bits(ULONG_MAX, 0);
printf("%u\n", n);
return (0);
}