Tybbow
Tybbow

Reputation: 11

C# how convert a string hex value in "bin" like xxd

I'm try a solution for convert a string hex value in format "binary" (.bin), like xxd command.

Example : I have a string hexValue "17c7dfef853adcddb2c4b71dd8d0b3e3363636363"

On linux, i want a result like next :

echo "hexvalue" > file.hex cat file.hex | xxd -r -p > file.bin

The hexdump of file.bin give :

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

0000010 36 36 36 36 36 36 36

My Program for convert this, is :

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);

So now, when look the hexdump of file2.bin, i see :

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

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

Why c3 or c2 exist in my new file ? Have you a solution for me ?

Thank for your help !

Upvotes: 1

Views: 1264

Answers (1)

Piotr Kasprzyk
Piotr Kasprzyk

Reputation: 81

The File.WriteAllText is used for text file writing and it encodes passed string in UTF-8. This is why your additional bytes occured in the output file.

Your desired effect suggests you need a binary file without in-process converting to UTF-32 string. Here is example of working version:

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);
    }
}

Upvotes: 1

Related Questions