How to replace hexadecimal value in a binary file?

8

Can you tell me how to replace the Hex value of a file with C #? Example: Replace 62 61 72 ( "bar" ) with 66 6F 6F ( "foo" ).

    
asked by anonymous 28.02.2014 / 15:01

3 answers

3

You will have to manually process the bytes in case of a binary file:

byte[] findBytes = { 0x62, 0x61, 0x72 };
byte[] replaceBytes = { 0x66, 0x6F, 0x6F };
List<byte> result;

using (var file = File.OpenRead(@"...origem..."))
{
    var allBytes = new byte[(int)file.Length];
    file.Read(allBytes, 0, (int)file.Length);
    result = new List<byte>(allBytes.Length);

    for (int itFile = 0; itFile < allBytes.Length; itFile++)
    {
        bool found = !findBytes
            .Where((t, i) => (i + itFile >= allBytes.Length)
                || (t != allBytes[i + itFile])).Any();

        if (found)
        {
            result.AddRange(replaceBytes);
            itFile += findBytes.Length - 1;
        }
        else
            result.Add(allBytes[itFile]);
    }
}

using (var file = File.Open(@"...destino...", FileMode.Create))
    file.Write(result.ToArray(), 0, result.Count);

This is a very rough implementation ... which reads all the bytes of the source and does all the processing in memory ... in case of very long files, you will probably have to subdivide the file and do the replacement part by piece.

    
28.02.2014 / 16:56
1

There is an excellent explanation in an original StackOverflow post in English:

p>

Adapted translation of the important part:

If you simply want to change the values of the bytes in the file, the most efficient approach in my opinion would be to open the file using a FileStream, find the proper position, and replace the bytes, as in the example below:

using (var stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite)) {
    stream.Position = 0;
    stream.WriteByte(0x66);
    stream.WriteByte(0x6F);
    stream.WriteByte(0x6F);
}
    
28.02.2014 / 15:34
-1

Try this: Hex to Decimal:

Convert.ToInt64(hexValue, 16);

Decimal for Hexadecimal:

string.format("{0:x}", decValue);
    
28.02.2014 / 15:08