2012-02-12 40 views
19

me encontré con el siguiente hexagonal camino de conversión binaria:Convertir cadena hexadecimal (hex) a una cadena binaria

String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16)); 

Si bien este enfoque funciona para los números hexadecimales pequeños, un número hexadecimal como la siguiente

A14AA1DBDB818F9759 

lanza una NumberFormatException.

lo tanto, escribió el siguiente método que parece funcionar:

private String hexToBin(String hex){ 
    String bin = ""; 
    String binFragment = ""; 
    int iHex; 
    hex = hex.trim(); 
    hex = hex.replaceFirst("0x", ""); 

    for(int i = 0; i < hex.length(); i++){ 
     iHex = Integer.parseInt(""+hex.charAt(i),16); 
     binFragment = Integer.toBinaryString(iHex); 

     while(binFragment.length() < 4){ 
      binFragment = "0" + binFragment; 
     } 
     bin += binFragment; 
    } 
    return bin; 
} 

El método anterior básicamente toma cada carácter en la cadena hexadecimal y lo convierte en sus equivalentes binarios con ceros si es necesario y luego lo une al valor de retorno. ¿Es esta una forma adecuada de realizar una conversión? ¿O estoy pasando por alto algo que puede hacer que mi enfoque fracase?

Gracias de antemano por cualquier ayuda.

+0

¿Sería mucho no trabajar por lo que están queriendo? También tiene ToBinaryString(). Eso sería apoyar ... rango va de -9.223.372.036.854.775.808 a 9.223.372.036.854.775.807. – Jared

+0

si eso hace lo que le gustaría, hágamelo saber para que pueda publicar la respuesta por favor. – Jared

+0

Tu código se ve bien para mí. También puede buscar en el siguiente enlace: http://java2everyone.blogspot.in/2009/04/java-hexadecimal-to-binary.html?m=1 –

Respuesta

34

BigInteger.toString(radix) va a hacer lo que quiere. Sólo tiene que pasar en un radix de 2.

static String hexToBin(String s) { 
    return new BigInteger(s, 16).toString(2); 
} 
+0

hecho. El único problema aquí es que los números crecen demasiado para caber en un 'int'. –

+0

Ese es el punto, lo siento. El desbordamiento es el problema con el código del OP, y esta solución lo soluciona. –

+0

@LouisWasserman, entendido. Muy bien. –

4
Integer.parseInt(hex,16);  
System.out.print(Integer.toBinaryString(hex)); 

Parse hex (String) a un entero con la base 16 después convertirlo a binario Cadena toBinaryString método (int) usando

ejemplo

int num = (Integer.parseInt("A2B", 16)); 
System.out.print(Integer.toBinaryString(num)); 

imprimirá

101000101011 

Max Hex vakue procesadas por los int es FFFFFFF

es decir, si FFFFFFF0 se pasa a ti dará error

2

Con todos los ceros:

static String hexToBin(String s) { 
    String preBin = new BigInteger(s, 16).toString(2); 
    Integer length = preBin.length(); 
    if (length < 8) { 
     for (int i = 0; i < 8 - length; i++) { 
      preBin = "0" + preBin; 
     } 
    } 
    return preBin; 
} 
1
public static byte[] hexToBin(String str) 
    { 
     int len = str.length(); 
     byte[] out = new byte[len/2]; 
     int endIndx; 

     for (int i = 0; i < len; i = i + 2) 
     { 
      endIndx = i + 2; 
      if (endIndx > len) 
       endIndx = len - 1; 
      out[i/2] = (byte) Integer.parseInt(str.substring(i, endIndx), 16); 
     } 
     return out; 
    } 
0
import java.util.*; 
public class HexadeciamlToBinary 
{ 
    public static void main() 
    { 
     Scanner sc=new Scanner(System.in); 
     System.out.println("enter the hexadecimal number"); 
     String s=sc.nextLine(); 
     String p=""; 
     long n=0; 
     int c=0; 
     for(int i=s.length()-1;i>=0;i--) 
     { 
      if(s.charAt(i)=='A') 
      { 
      n=n+(long)(Math.pow(16,c)*10); 
      c++; 
      } 
     else if(s.charAt(i)=='B') 
     { 
      n=n+(long)(Math.pow(16,c)*11); 
      c++; 
     } 
     else if(s.charAt(i)=='C') 
     { 
      n=n+(long)(Math.pow(16,c)*12); 
      c++; 
     } 
     else if(s.charAt(i)=='D') 
     { 
      n=n+(long)(Math.pow(16,c)*13); 
      c++; 
     } 
     else if(s.charAt(i)=='E') 
     { 
      n=n+(long)(Math.pow(16,c)*14); 
      c++; 
     } 
     else if(s.charAt(i)=='F') 
     { 
      n=n+(long)(Math.pow(16,c)*15); 
      c++; 
     } 
     else 
     { 
      n=n+(long)Math.pow(16,c)*(long)s.charAt(i); 
      c++; 
     } 
    } 
    String s1="",k=""; 
    if(n>1) 
    { 
    while(n>0) 
    { 
     if(n%2==0) 
     { 
      k=k+"0"; 
      n=n/2; 
     } 
     else 
     { 
      k=k+"1"; 
      n=n/2; 
     } 
    } 
    for(int i=0;i<k.length();i++) 
    { 
     s1=k.charAt(i)+s1; 
    } 
    System.out.println("The respective binary number is : "+s1); 
    } 
    else 
    { 
     System.out.println("The respective binary number is : "+n); 
    } 
    } 
} 
Cuestiones relacionadas