Writting Hex String to a binary file.

Hi, i have a string variable with a hex bytes sequence.

Example:
string strHex = "AA BB CC";
                       ^  ^  ^
                       1   2   3 bytes


public static void WriteNewBytesToFile(String FileName, String Offset, String NewHexBuff)

{

logtxt("Writing to file ...");

FileStream fs = File.OpenWrite(FileName);

BinaryWriter bw = new BinaryWriter(fs);

//When i do bw.Write(NewHexBuff);  it writes the NewHexBuff as a string and not as a binary buff

bw.Close();

fs.Close();

logtxt("Writting finished!");

}

I need write this sequence to a binary file, but treating it as a binary buffer.

Can anybody help me



Answer this question

Writting Hex String to a binary file.

  • scotcurry



    string hexString = "414243";
    for (int i = 0; i < hexString.Length; i += 2)
    {
        int c = int.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
        bw.Write(Convert.ToChar(c));
    }

     


  • Mr. Mort

    No, that will have a 0 for every other byte - a Char is 16 bits in .NET.

    I suggest that the OP abandons a BinaryWriter unless he needs it for another reason, and just uses a Stream. Create a byte array as a buffer, parse the hex into bytes (preferrably without using Substring all over the place - it's easy enough to do without), and then write those bytes out. Repeat until all the data has been written out.

    Jon



  • Writting Hex String to a binary file.