Error in creating BIN File using Binary File C#

I am creating a Binary File in C# here using the following code below. It is relatively simple code below. The RawData variable is a type string[].

     using (BinaryWriter bin = new BinaryWriter(File.Open("file.bin", FileMode.Create)))
        {
            foreach (string data in RawData)
            {
                int Byte = Convert.ToInt32(data, 16);
                bin.Write(Byte);


            }

        }

Unfortunately the BIN File is produced like this. It places the correct byte value but then skips the next three bytes and places zeros there and then places the next byte value. Does anyone know why this happens. I have used debugged and the bin.Write(Byte), and these extra zeros are NOT sent to this method.

BIN File Capture

Jon Skeet
people
quotationmark

You're using BinaryWriter.Write(int). So yes, it's writing 4 bytes, as documented.

If you only want to write one byte, you should use BinaryWriter.Write(byte) instead.

So you probably just want:

bin.Write(Convert.ToByte(data, 16));

Alternatively, do the whole job in two lines:

byte[] bytes = RawData.Select(x => Convert.ToByte(x, 16)).ToArray();
File.WriteAllBytes("file.bin", bytes);

people

See more on this question at Stackoverflow