Problem 12: Write a program to convert a decimal number to binary number.
Solution: We can do this in two ways. First one is very common. Every time we divide the number by 2 keeping the remainder into an array. That is...
#include<stdio.h>
void Binary(int n) {
int digit[100], int index = 0;
while(n) { // n!= 0 or n > 0
digit[index++] = n%2;
n /= 2;
}
for(int i = index-1; i>=0; i--) {
printf("%d",digit[i]);
}
}
int main() {
int n;
scanf("%d",&n);
Binary(n);
return 0;
}
|
For very biginners, the above program works this way:
let n = 10;
n = 10, n > 0 ? true, then digit[0] = n%2 = 0, n = n/2 = 5
n = 5, n> 0 ? true, digit[1] = n%2 = 1, n = n/2 = 2
n = 2, n > 0 ? true, digit[2] = n%2 = 0, n = n/2 = 1
n = 1, n > 0? true, digit[3] = n%2 = 1, n = n/2 = 0
n = 0, n > 0 ? false, break;
Finally print the digit array from last index. why does from last index ? try to find the answer.
2nd Solution:
#include<stdio.h>
void Binary(int n) {
int i, bits = 32768;
int k;
for(i = 0; i<15; i++) {
printf("%d", ( n & bits ) ? 1 : 0 );
n <<= 1;
}
}
int main() {
int n;
scanf("%d",&n);
Binary(n);
return 0;
}
|
int n = 10;
int k = n<<1;
what is the value of k ? lets see...
binary form of 10 is: 0000000000001010 ( assume integer is 16 bits)
then n<<1 = 0000000000010100 ( that is remove 1 bit from left most side and append it to the right side)
Aagain:
k = n>>1 , k = ? try yourself.We do not need this operator for thie problem.
our Second Solution:
Above function converts a decimal number to equivalent binary number.
Before analysis, we have to remove confusion about print function. Here is given printf("%d", (n & bits) ? 1:0);
This means that:
if(n & bits) {
printf("1");
}else {
printf("0");
}
lets n = 10, we know its binary form is: 0000000000001010
First time:
n & 32768, what do we mean by this ?
n = 0000000000001010
32768 = 1000000000000000
consider the left most digit of both number, n obtains 0 and 32768 obtains 1, so
n & 32768 = 0 & 1 = 0 ( and 0 means false in C/C++, so this time 0 will be printed)
and n <<= 1 = 0000000000010100
2nd time:
Same, 0 will be printed and n <<= 0000000000101000
.....
....
....
Once n will be = 1010000000000000
So, n & 32768 = 100000000000000 & 1010000000000000 = 1 ( both have 1 at the left most side) and 1 will be printed
Finally we will see on the screen for input 10:
0000000000001010
Back to Problem list