Bitwise Operations to Count the Number of
Leading Zero’s in a Number x
#include
#include
#define num_bits_int (sizeof(int)*8)
int find(int);
void main()
{
int
n, i, a, count = 0, flag = 1, m = 1, j, cmp;
clrscr();
printf("Enter
the number\n");
scanf("%d", &n);
a =
n >> 31 & 1;
if
(a == 0)
{
for (i = (num_bits_int)-1;i >= 0;i--)
{
a = (n >> i)& 1;
if (a == 0)
{
count++;
}
else
{
for (j = n + 1;;j++)
{
cmp = find(j);
if (cmp ==
(((num_bits_int)-1) - count) + 1)
{
printf("next
higher power -> %d\n", j);
break;
}
}
break;
}
}
}
else
{
for (i = (num_bits_int)-1;i >= 0;i--)
{
a = (n >> i)& 1;
if (a == 1)
{
count++;
}
else
{
for (j = n + 1;;j++)
{
cmp = find(j);
if (cmp ==
(((num_bits_int)- 1) - count))
{
printf("next
higher power -> %d\n", j);
break;
}
}
break;
}
}
}
}
int find(int n)
{
int
count = 0, a, flag = 1, i;
for
(i = 0;i <= (num_bits_int) - 1;i++)
{
a = (n >> i) & 1;
if (a == 1 && flag == 1)
{
return count;
}
else
{
count++;
flag = 1;
}
}
getch();
}
Output
Enter the number
9
next higher power
-> 16
Enter the number
-20
next higher power
-> -16
Enter the number
44
next higher power
-> 64
Enter the number
-7
next higher power
-> -4
Enter the number
-31
next higher power
-> -16
Enter the number
-56
next higher power
-> -32
Enter the number
34
next higher power
-> 64
Count the Number of Bits needed to be Flipped to Integer X to Generate Integer Y
#include
#include
#define num_bits_int (sizeof(int)*8)
void main()
{
int n, m, i, count = 0, a, b;
printf("Enter the number\n");
scanf("%d", &n);
printf("Enter another number\n");
scanf("%d", &m);
for (i = num_bits_int-1;i >= 0;i--)
{
a = (n >> i)& 1;
b = (m >> i)& 1;
if (a != b)
count++;
}
printf("flip count = %d\n", count);
getch();
}
Output
Enter the number
127
Enter another number
125
flip count = 1
Enter the number
127
Enter another number
128
flip count = 8
Enter the number
42
Enter another number
21
flip count = 6
No comments:
Post a Comment