tennis779
tennis779

Reputation: 348

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

Upvotes: 0

Views: 239

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500665

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

Upvotes: 3

Scott Langham
Scott Langham

Reputation: 60311

Try

var Byte = Convert.ToByte(....)

instead.

You're converting to int, each of which is 4 bytes. So, you see three of them are all zero, and just one byte of the int is the value you expect.

Upvotes: 2

Related Questions