Would there be a way to solve this problem using only repetition, div and mod, without using vector or a specific function for conversion?
Would there be a way to solve this problem using only repetition, div and mod, without using vector or a specific function for conversion?
You can implement a function to do this conversion:
long dec2bin( long dec )
{
int resto;
long bin = 0;
int i = 1;
while( dec != 0 )
{
resto = dec % 2;
dec /= 2;
bin += resto * i;
i *= 10;
}
return bin;
}
Code tested:
#include <stdlib.h>
#include <stdio.h>
long dec2bin( long dec )
{
int resto;
long bin = 0;
int i = 1;
while( dec != 0 )
{
resto = dec % 2;
dec /= 2;
bin += resto * i;
i *= 10;
}
return bin;
}
int main( void )
{
long i = 0;
for( i = 0; i < 32; i++ )
printf( "%ld = %ld\n", i, dec2bin( i ) );
return 0;
}
Output:
0 = 0
1 = 1
2 = 10
3 = 11
4 = 100
5 = 101
6 = 110
7 = 111
8 = 1000
9 = 1001
10 = 1010
11 = 1011
12 = 1100
13 = 1101
14 = 1110
15 = 1111
16 = 10000
17 = 10001
18 = 10010
19 = 10011
20 = 10100
21 = 10101
22 = 10110
23 = 10111
24 = 11000
25 = 11001
26 = 11010
27 = 11011
28 = 11100
29 = 11101
30 = 11110
31 = 11111