Saltar al contenido

103 ejemplo de código binario a decimal

Ejemplo 1: binario a 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] != ''&&binary[d] != '.') { d++; }
	d--;
	if (binary[0] == '-') {
		while (binary[k] != '') {
			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] != ''&&binary[i] != '.') {
		i++;
	}
	i--;
	count = i;
	h = i;
	while (binary[h] != '') {
		floa[g] = binary[h + 2];
		g++;
		h++;
	}
	g--;
	count1 = g;
	while (i >= 0) {
		binary2[j] = binary[i];
		i--;
		j++;
	}
	binary2[j] = '';
	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;
}

Ejemplo 2: binario a decimal

import java.util.Scanner;

public class BinaryToDecimal {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		String binary = sc.next();
		// This is one line solution for binary to decimal in java
		System.out.println(Integer.parseInt(binary,2));
		
		//This solution is based on formula for binary to decimal conversion
		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);

	}

}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *