2012-09-22 5 views
1

Dans le programme suivant, je suis en train de convertir une chaîne hexadécimale "ABCDEF" en binaire.convertir efficacement hexadécimal en binaire

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    String key = "ABCDEF"; //hexadecimal key 
    char[] keyCharArray = key.toCharArray(); 
    for (int i = 0; i < key.length(); i++) { 
     System.out.print(HexToBinary((keyCharArray[i]))+","); 
    } 
} 

public static String HexToBinary(char Hex) { 
    int i = Integer.parseInt(Character.toString(Hex), 16); 
    String Bin = Integer.toBinaryString(i); 
    return Bin; 
} 

Je reçois la sortie suivante

0,1,10,11,100,101,110,111,1000,1001,1010,1011,1100,1101,1110,1111, 

mais j'exiger que la sortie soit comme suit

0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111, 

d'une façon que je trouve est annexant 0x en face de chaque caractère hexagonal . comme suit:

0x0, 0x1, 0x2,............,0xE,0xF 

une autre façon est de vérifier manuellement le nombre de caractères de la sortie est courte de 4, et append ces nombreux l » 0 à lui. Mais je ne sais pas comment implémenter le premier dans le code ci-dessus. Existe-t-il une méthode efficace pour faire ce que j'essaye de faire ci-dessus?

Répondre

3

Vous pouvez toujours faire une recherche statique:

private static String[] staticLookup = new String[] 
    {0000,0001,0010,0011,0100,0101,0110,0111, 
    1000,1001,1010,1011,1100,1101,1110,1111}; 


public static String HexToBinary(char Hex) { 
    return staticLookup[Integer.parseInt(Character.toString(Hex), 16)]; 
} 
+0

+1 Bien! Pas besoin de compliquer les choses – gtgaxiola

+0

Merci, les deux réponses sont correctes selon mes exigences, mais je préfère aller pour l'efficacité, merci :) – md1hunox

2

utilisent simplement un switch pour déterminer le nombre de zéros manquants:

switch(i){ 
    case 0: case 1: return "000" + Integer.toBinaryString(i); 
    case 2: case 3: return "00" + Integer.toBinaryString(i); 
    case 4: case 5: case 6: case 7: return "0" + Integer.toBinaryString(i); 
    default: return Integer.toBinaryString(i); 
} 
6
String.format("%04d", yournumber); 

Pour être clair:

public static String HexToBinary(char Hex) { 
    int i = Integer.parseInt(Character.toString(Hex), 16); 
    return String.format("%04d", Integer.parseInt(Integer.toBinaryString(i))); 
} 
+0

Il n'a pas de numéro, il a une chaîne. Donc, 'String.format ("% 04s ", Bin)'. –

+1

Cela va créer la chaîne à partir du nombre avec remplissage. Vérifiez sa méthode HexToBinary() où il crée int i – gtgaxiola

+0

@Joao Oh, vous vouliez dire la variable "yournumber", je donnais juste un cas général de la méthode() ... – gtgaxiola

Questions connexes