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?

Dani AI

Generated

The thread already highlights the two root causes: the algorithm must both remove the bit just read and print digits in the correct order (as and pointed out), and common C errors (missing & in scanf, wrong loop conditions) cause undefined behavior. ’s byte-wise print is useful when an 8-bit view is wanted, but a general converter should produce a minimal-width binary string and accept arbitrary-length binary input.

A compact, robust example follows. It accepts a line of input and treats it as a decimal number unless it’s a binary string (optionally prefixed with 0b); decimal->binary uses shifting and a small buffer, binary->decimal accumulates by left-shifting. The code checks input characters and handles zero.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_binary_ull(unsigned long long n) {
    if (n == 0) { putchar('0'); putchar('\n'); return; }
    char buf[65];
    int i = 0;
    while (n) {
        buf[i++] = (n & 1) ? '1' : '0';
        n >>= 1;
    }
    while (--i >= 0) putchar(buf[i]);
    putchar('\n');
}

unsigned long long binary_to_ull(const char *s) {
    unsigned long long v = 0;
    for (; *s; ++s) {
        if (*s != '0' && *s != '1') break;
        v = (v << 1) | (unsigned long long)(*s - '0');
    }
    return v;
}

int main(void) {
    char line[128];
    if (!fgets(line, sizeof line, stdin)) return 0;
    line[strcspn(line, "\r\n")] = '\0';
    const char *p = line;
    if (p[0] == '0' && (p[1] == 'b' || p[1] == 'B')) p += 2;
    int is_bin = (*p != '\0');
    for (const char *q = p; *q; ++q) if (*q != '0' && *q != '1') { is_bin = 0; break; }
    if (is_bin) {
        unsigned long long val = binary_to_ull(p);
        printf("%llu\n", val);
    } else {
        char *end;
        unsigned long long dec = strtoull(line, &end, 10);
        print_binary_ull(dec);
    }
    return 0;
}

Troubleshooting notes: missing & in scanf is a frequent cause of crashes (seen in ’s post). Prefer fgets + parsing to avoid buffer/format issues. For very large inputs, validate overflow (functions like strtoull set errno on overflow). For fixed-width output (always 8/16/32 bits) the bitmask approach from is appropriate; for minimal-length binary the buffering-and-reverse method above is clearer. Compile with warnings enabled (e.g., gcc -Wall -Wextra) to catch simple mistakes early.

Recommended Answers

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 meeting, networking, learning, and sharing knowledge.