Created
June 9, 2014 17:55
-
-
Save cynx/ce61d4c95033f182d5ae to your computer and use it in GitHub Desktop.
C program to covert 'Decimal to Binary' and 'Binary to Decimal'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* C programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */ | |
/* From http://www.programiz.com/ */ | |
#include <stdio.h> | |
#include <math.h> | |
int binary_decimal(int n); | |
int decimal_binary(int n); | |
int main() | |
{ | |
int n; | |
char c; | |
printf("Instructions:\n"); | |
printf("1. Enter alphabet 'd' to convert binary to decimal.\n"); | |
printf("2. Enter alphabet 'b' to convert decimal to binary.\n"); | |
scanf("%c",&c); | |
if (c =='d' || c == 'D') | |
{ | |
printf("Enter a binary number: "); | |
scanf("%d", &n); | |
printf("%d in binary = %d in decimal", n, binary_decimal(n)); | |
} | |
if (c =='b' || c == 'B') | |
{ | |
printf("Enter a decimal number: "); | |
scanf("%d", &n); | |
printf("%d in decimal = %d in binary", n, decimal_binary(n)); | |
} | |
return 0; | |
} | |
int decimal_binary(int n) /* Function to convert decimal to binary.*/ | |
{ | |
int rem, i=1, binary=0; | |
while (n!=0) | |
{ | |
rem=n%2; | |
n/=2; | |
binary+=rem*i; | |
i*=10; | |
} | |
return binary; | |
} | |
int binary_decimal(int n) /* Function to convert binary to decimal.*/ | |
{ | |
int decimal=0, i=0, rem; | |
while (n!=0) | |
{ | |
rem = n%10; | |
n/=10; | |
decimal += rem*pow(2,i); | |
++i; | |
} | |
return decimal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#include<stdio.h>
#include<stdlib.h>
int main()
{
int decNumber,*arr,counter=0,loop=0,rem=0,copy1,copy2;
printf("\nEnter a Decimal Number:");
scanf("%d",&decNumber);
copy1=decNumber;
copy2=decNumber;
while(copy1 != 0)
{
counter++;
copy1/=2;
}
arr=(int *)calloc(counter,sizeof(int));
for(loop=0;loop<counter;loop++)
{
rem=copy2%2;
arr[loop]=rem;
copy2/=2;
}
printf("\nThe Binary representation of %d is: ",decNumber);
for(loop=counter-1;loop>=0;loop--)
{
printf("%d",arr[loop]);
}
}