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?

Recommended Answers

You don't have any divide's in there. You can't just use modulo for the whole thing. Also, you forgot to read the number backwards.

Jump to Post

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 until val is 0.

Jump to Post

All 5 Replies

You don't have any divide's in there. You can't just use modulo for the whole thing. Also, you forgot to read the number backwards.

/*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);	
}
commented: 1. Don't give away free code. 2. That code is bad. -1

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?

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 until val is 0.

could you pls. do me a program that converting a binary to decimal or decimal to binary with a simple codes in turbo c, which i can easily understand.. for example i will enter an number 1 then it will be automatically to convert it to its binary value. thank u! i will wait for your help! pls. help me..

commented: What a BOZO! With the answer right in this thread you have to post this message? -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.