This code is an example from a book that the problem require to change decimal to binary number using bitwise AND
operator and the shift
operator.
I cannot understand the code although had tried to understand this code using debug compiler.
Suppose that for a
and b
the user input is 10
and 8
#include <stdio.h>
#include <stdlib.h>
int count_bits (unsigned x)
{
int bits=0;
while(x){
if (x&1U)bits++;
x>>=1;
} return bits;
}
int int_bits(void)
{
return count_bits(~0U);
}
void print_bits(unsigned x)
{
int i;
for(i=int_bits(x)-1;i>=0;i--)
putchar(((x>>i)&1U)?'1':'0');
}
int main(void)
{
unsigned a,b; /*suppose user input a=10 b=8*/
printf("enter two positive integer value=\n");
printf("a= "); scanf("%u",&a);
printf("b: "); scanf("%u",&b);
printf("\na ="); print_bits(a);
printf("\na ="); print_bits(b);
return 0;
}
In int_bits
function what actually (~0U)
does? I this meaning to change 0
to 1
?
I know it calls count_bits
function and return count bits(~0) value but why the x
here is somewhat random memory address like 4294967295
?
Maybe is it because int int_bits(void)
and int_bits()
so no parameter and x
change from 10
to a random address?
And the count_bits
function is here to count how many bits?
while (4294967295) {
if(x&1u)-> (means compare x last digit value with 1) if true, bits ++;
x>>=1; }-> this mean to shift 1 digit of x to right which mean to divide with 2 until quotien is 0
and when I tried to debug I got 32
for bits value
Why produce 32
? is this relate to (~0U)
so all bits were 1
or the remains of division?
print_bits (unsigned x) function, is to produce the result
for(i=int_bits()-1;i>=0;i--)
putchar(((x>>i)&1u)?'1':'0')
the x in this value is 10,8 (user input)
and i is 31 from return bits
32-1=31 will be looping until 0
10>>30
means shift 31
to right in just 10
?
How it can produce 1010
?
What this code actually compare to produce 1010
?
Actually the program also produce 32
digit with 1010
in the end.