convert binary to decimal C code example

Example 1: binary to decimal in c

#include <math.h>
#include <stdio.h>
int convert(long long n);
int main() {
    long long n;
    printf("Enter a binary number: ");
    scanf("%lld", &n);
    printf("%lld in binary = %d in decimal", n, convert(n));
    return 0;
}

int convert(long long n) {
    int dec = 0, i = 0, rem;
    while (n != 0) {
        rem = n % 10;
        n /= 10;
        dec += rem * pow(2, i);
        ++i;
    }
    return dec;
}

Example 2: binary to decimal

double binaryToDecimal(char binary[DIM]) {
	char binary2[DIM] = "", floa[DIM] = "";
	double decimal = 0, negDec = 0, flo = 0;
	int count = 0, j = 0, i = 0, f = 0, g = 0, h = 0, count1 = 0, d = 0, k = 0;
	while (binary[d] != '\0'&&binary[d] != '.') { d++; }
	d--;
	if (binary[0] == '-') {
		while (binary[k] != '\0') {
			binary[k] = binary[k + 1];
			k++;
		}
		k = 0;
		while (binary[k] == '0') {
			d--;
			k++;
		}
		negDec = pot(2.000, d*1.000, 1);
	}
	while (binary[i] != '\0'&&binary[i] != '.') {
		i++;
	}
	i--;
	count = i;
	h = i;
	while (binary[h] != '\0') {
		floa[g] = binary[h + 2];
		g++;
		h++;
	}
	g--;
	count1 = g;
	while (i >= 0) {
		binary2[j] = binary[i];
		i--;
		j++;
	}
	binary2[j] = '\0';
	while (i <= count) {
		if (binary2[i] == '1') {
			decimal = decimal + pot(2.000, i, 1);
		}
		i++;
	}
	h = -1;
	g = 0;
	while (g <= count1) {
		if (floa[g] == '1') {
			flo = flo + pot(2.000, h, 1);
		}
		g++;
		h--;
	}
	decimal = decimal + flo;
	if (negDec > 0) {
		decimal = (decimal - negDec);
		if (flo > 0) {
			double f = fl(decimal);
			f = 1 - f;
			decimal = returnDeciPart(decimal) - f;
		}
	}
	return decimal;
}

Example 3: binary to decimal

= (11001010)2
= 1x27+1x26+0x25+0x24+1x23+0x22+1x21+0x20
= 128+64+0+0+8+0+2+0
= (202)10

Tags:

Cpp Example