0% found this document useful (0 votes)
102 views3 pages

C Program To Convert Binary To Decimal and Vice Versa

Uploaded by

rajatvernekar40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views3 pages

C Program To Convert Binary To Decimal and Vice Versa

Uploaded by

rajatvernekar40
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

C program to convert binary to Decimal and vice versa

#include <stdio.h>

#include <math.h>

#include <string.h>

int binaryToDecimal(const char *binary) {

int decimal = 0;

int length = strlen(binary);

for (int i = 0; i < length; i++) {

if (binary[length - 1 - i] == '1') {

decimal += pow(2, i);

return decimal;

void decimalToBinary(int decimal, char *binary) {

int index = 0;

while (decimal > 0) {

binary[index++] = (decimal % 2) + '0';

decimal /= 2;

binary[index] = '\0';

for (int i = 0; i < index / 2; i++) {

char temp = binary[i];

binary[i] = binary[index - i - 1];

binary[index - i - 1] = temp;
}

int main() {

int choice, decimal;

char binary[32];

printf("Choose conversion type:\n");

printf("1. Binary to Decimal\n");

printf("2. Decimal to Binary\n");

printf("Enter your choice (1 or 2): ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter a binary number: ");

scanf("%s", binary);

printf("Decimal: %d\n", binaryToDecimal(binary));

break;

case 2:

printf("Enter a decimal number: ");

scanf("%d", &decimal);

decimalToBinary(decimal, binary);

printf("Binary: %s\n", binary);

break;

default:

printf("Invalid choice!\n");

break;
}

return 0;

OUTPUT:

Choose conversion type:

1. Binary to Decimal

2. Decimal to Binary

Enter your choice (1 or 2): 2

Enter a decimal number: 125

Binary: 1111101

You might also like