0% found this document useful (0 votes)
27 views

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)
27 views

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
You are on page 1/ 3

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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy