binary to decimal representation code example
Example 1: 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 2: binary to decimal
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String binary = sc.next();
System.out.println(Integer.parseInt(binary,2));
int n=0,dec=0;
for(int i=binary.length()-1;i>=0;i--)
{
dec = dec + Integer.parseInt(String.valueOf(binary.charAt(i)))*(int)Math.pow(2,n);
n++;
}
System.out.println(dec);
}
}