1
There would be a way to solve this problem using just repetition, div and mod, without using vector or a specific function for conversion?
1
There would be a way to solve this problem using just repetition, div and mod, without using vector or a specific function for conversion?
3
You can implement a function to make 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;
}
Exit:
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
That’s not quite right. See why in this other question.
Browser other questions tagged c
You are not signed in. Login or sign up in order to post.
One option is bit operations. Like this elegant solution.
– Lorhan Sohaky
The question is wide and outside the scope, the purpose of the site is not to do the task of people, besides it has already been answered. In addition to the question not being clear, it made in a crooked way. The answers in the original question speaks of it. There is no binary number. What has been answered here is an atrocity trying to make a decimal number look binary, but this is conceptually wrong.
– Maniero