Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SohanChy/bff3490f203b91c5284e to your computer and use it in GitHub Desktop.
Save SohanChy/bff3490f203b91c5284e to your computer and use it in GitHub Desktop.
Simple basic C program to Convert Numbers to Binary
#include<stdio.h>
int main(void) {
int input,binary=0,x;
//Take and see if input is a positive number
do {
printf("Please enter POSITIVE a number:");
scanf("%d",&input);}
while(input<0);
x=input;
//Convert to binary
//Using 0 causes problems, so using 9 instead of 0
while(x!=0)
{
binary=binary*10;
if(x%2==1){
binary=binary+1;
}
if(x%2==0){
binary=binary+9;
}
x=x/2;
}
//Its in binary but its reversed
//The 0s are in 0 we need to fix that as well
//reverse and replace here
int temp=binary,reverse=0,y;
while(temp!=0)
{
y=temp%10;
if(y==9){y=0;}
reverse=(reverse*10)+y;
temp=temp/10;
}
//Print the result
printf("\n\t\t\t%d",reverse);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment