converting from binary to decimal and vice versa
hello there, I am working on a small c program that automatically detects whether the input given is a decimal number or a binary number and coverts accordingly.
what is the best way to convert a binary number to a decimal number and a decimal number to a binary number.
i found this to be the easiest when converting from binary to deicmal
http://www.wikihow.com/Convert-from-Decimal-to-Binary
but my program doesnt work..?
/*decimal to binary*/
#include <stdio.h>
int main() {
int dec;
int hold=0;
printf("decimal number : ");
scanf("%d",&dec);
hold=dec%2;
while (hold!=1){
if (hold == 0){
printf("0");
}else if(hold >1){
printf("1");
}else{
printf("1");
}
hold=hold%2;
}
}
what have i done wrong?
revenge2
Junior Poster in Training
79 posts since Feb 2007
Reputation Points: 10
Solved Threads: 2
/*decimal to binary*/
#include <stdio.h>
void printBinary(const unsigned char val) {
for(int i = 7; i >= 0; i--)
if(val & (1 << i))
printf("1");
else
printf("0");
printf("\n");
}
int main() {
int dec;
int hold=0;
printf("Integer number : ");
scanf("%d",&dec);
printBinary((unsigned char)dec);
}
ambarisha.kn
Junior Poster in Training
66 posts since Jun 2008
Reputation Points: 25
Solved Threads: 0
hmmm why doesn't this work?
#include <stdio.h>
void bin_c(int x);
int main(){
int x;
printf("Enter a number:");
scanf("%d",x);
bin_c(x);
return 0;
}
void bin_c(int x){
if (x == 1){
printf("1");
}
while (x!=1){
int y;
y=x/2;
if (y == 0){
printf("0");
}
if (y > 1){
printf("1");
}
if (y == 1){
printf("1");
}
bin_c(y);
}
}
i know i have to reverse the order but this doesnt work why is this?
revenge2
Junior Poster in Training
79 posts since Feb 2007
Reputation Points: 10
Solved Threads: 2
To get a binary value from a decimal value
v = val %2; --v will contain the value of the ones digit. Then, after you get the digit, remove it to get the next digit:
v = val /2;
Loop untilval is 0.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944