2017-04-13 3 views
0

Je suis essayer une solution pour convertir une valeur de chaîne hexadécimale au format "binaire" (.bin), comme commande xxd.C# comment convertir une valeur hexadécimale de chaîne dans "bin" comme xxd

Exemple: J'ai une chaîne hexValue "17c7dfef853adcddb2c4b71dd8d0b3e3363636363"

Sur linux, je veux un résultat comme suivant:

echo "HexValue"> file.hex chat file.hex | xxd -r -p> file.bin

Le hexdump de file.bin donner:

0000000 17 c7 ef df 85 3a cc dd b2 c4 b7 1d d8 d0 b3 e3

Mon programme pour convertir cela, est:

Private static string convertHex(string value) 
{ 
    string[] hexVal = value.Split(' '); 
    StringBuilder s = new StringBuilder(); 

    foreach (string hex in hexVal) 
    { 
     int val = Convert.ToInt32(hex, 16); 
     string stringValue = char.ConvertFromUtf32(val); 
     s.Append(stringValue); 
    } 
    return s.ToString(); 
} 

string MyString = "17 c7 df ef 85 3a dc dd b2 c4 b7 1d d8 d0 b3 e3 36 36 36 36 36"; 
string newString = converthex(MyString); 
Console.WriteLine(newString); 
File.WriteAllText("file2.bin", newString); 

Alors maintenant, wh en regard de la hexdump file2.bin, je vois:

0000000 17 c3 c3 87 97 c3 c2 af 85 3a c3 c3 9c 9d c2 b2

0000010 84 c3 c2 b7 1d c3 c3 98 90 c2 b3 a3 36 36 36

Pourquoi c3 ou c2 existe-t-il dans mon nouveau fichier? Avez-vous une solution pour moi?

Merci pour votre aide!

Répondre

0

Le File.WriteAllText est utilisé pour l'écriture de fichiers texte et il code la chaîne transmise en UTF-8. C'est pourquoi vos octets supplémentaires se sont produits dans le fichier de sortie.

L'effet souhaité suggère que vous avez besoin d'un fichier binaire sans conversion en cours de traitement en chaîne UTF-32. Voici un exemple de la version de travail:

class Program 
{ 
    private static byte[] convertHex(string value) 
    { 
     string[] hexVal = value.Split(' '); 
     byte[] output = new byte[hexVal.Length]; 
     var i = 0; 
     foreach (string hex in hexVal) 
     { 
      byte val = (byte)(Convert.ToInt32(hex, 16)); 
      output[i++] = val; 
     } 
     return output; 
    } 
    static void Main(string[] args) 
    { 
     string MyString = "17 c7 df ef 85 3a dc dd b2 c4 b7 1d d8 d0 b3 e3 36 36 36 36 36"; 
     var file = new FileStream("file2.bin", FileMode.Create); 
     var byteArray = convertHex(MyString); 
     file.Write(byteArray, 0, byteArray.Length); 
    } 
} 
+0

Hum, ok, c'est mon faux.Mon programme doit calculer le md5sum dans la chaîne hexagonale; dans le format binaire. Mais, je n'ai pas vu, ma fonction md5 c'est l'appel avec utf8.getstring. D'accord, c'est bon, avec votre aide. Je vous remercie. Un jour pour cela .. OMG !! – Tybbow