Decimal to binary algorithm in C
Solution 1
When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
Solution 2
If you know the algorithm there's no reason not to use itoa
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int n;
char output[100];
printf("Enter a number: ");
scanf("%d", &n);
itoa(n, output, 2); //2 means base two, you can put any other number here
printf("The number %d is %s in binary.", n, output);
return 0;
}
Solution 3
How does the conversion works?
/* Example:
125(10) -----> ?(2) 125 |_2
-1- 62 |_2
-0- 31 |_2
-1- 15 |_2
-1- 7 |_2
-1- 3 |_2
-1- 1 */
So in this example the binary number for 125(10) is 1111101(2), and this is the process I describe in my function.
/* Functions declaration (Prototype) */
int wordCalculator( int * const word, long int number, int base );
int main( void )
{
int i, base;
int word[ 32 ];
unsigned long int number;
printf( "Enter the decimal number to be converted: " );
scanf( "%ld", &number );
printf( "\nEnter the new base: " );
scanf( "%d", &base );
i = wordCalculator( word, number, base );
printf( "The number is: " );
for(; i >= 0; i--){
if ( word[ i ] <= 9)
printf( "%d", word[ i ] );
else
/* 65 represents A in ASCII code. */
printf( "%c", ( 65 - 10 + word[ i ] ) );
}
printf( "\n" );
}
int wordCalculator( int * const word, long int number, int base )
{
unsigned long int result = number;
int i, difference;
i = 0;
do{
difference = result % base;
result /= base;
*( word + i ) = difference;
i++;
if ( result < base )
*( word + i ) = result;
} while( result >= base );
return i;
}
Tudor Ciotlos
Experienced Developer with a demonstrated history of working in the information technology, consultancy and banking industries. I consider myself to be a T-Shaped Developer (a generalizing specialist) with focus on Frontend Development. ⚙️ Skills: Full Stack Web Development with JavaScript (ES5, ES6, ESNext), Angular 2+, React, Electron, Node.js, D3.js, Highcharts, TypeScript, Java, Git, SQL, HTML5, CSS3 and others
Updated on March 21, 2020Comments
-
Tudor Ciotlos about 4 years
I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (e.g. for 1993 I get 1420076519).
int aux=x; long bin=0; while (aux>0) { bin=bin*10+aux%2; aux=aux/2; } printf("%d in decimal is %ld in binary.", x, bin);