The decimal to binary conversion C program example

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Converting the decimal value input by user from standard output to the binary equivalent

To show: The decimal to binary conversion C program example

 

 

#include <stdio.h>

/* prototype to convert decimal to binary function */

void dectobin();

int main(void)

{

char chs = 'Y';

do

{

dectobin();

printf("Again? Y, others to exit: ");

chs = getchar();

scanf("%c", &chs);

}while ((chs == 'Y') || (chs == 'y'));

return 0;

}

void dectobin()

{

int input;

printf("Enter decimal number: ");

scanf("%d", &input);

if (input < 0)

printf("Enter unsigned decimal!\n");

/* for the mod result */

int i;

/* count the binary digits */

int count = 0;

/* storage */

int binbuff[64];

 

do

{

/* Modulus 2 to get the remainder of 1 or 0 */

i = input%2;

/* store the element into the array */

binbuff[count] = i;

/* Divide the input by 2 for binary decrement */

input = input/2;

/* Count the number of binary digit */

count++;

/* repeat */

}while (input > 0);

/* prints the binary digits */

printf ("The binary representation is: ");

 

do

{

printf("%d", binbuff[count - 1]);

count--;

if(count == 8)

printf(" ");

} while (count > 0);

 

printf ("\n");

}

 

Output example:

 

Enter decimal number: 100

The binary representation is: 1100100

Again? Y, others to exit: y

Enter decimal number: 13

The binary representation is: 1101

Again? Y, others to exit: y

Enter decimal number: 20000

The binary representation is: 1001110 00100000

Again? Y, others to exit: Y

Enter decimal number: 12345

The binary representation is: 110000 00111001

Again? Y, others to exit: y

Enter decimal number: 7654321

The binary representation is: 111010011001011 10110001

Again? Y, others to exit: h

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index