0

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

2
  • 1
    Use Convert.ToByte, and a byte type. sizeof(int) == 4. Commented Aug 8, 2014 at 15:20
  • I am having trouble now when adding this code to my Forms Application. When I tested this in my simple Console app it worked beautifully. Now I moved this code into an Event Handler in my Forms application, and it is producing a terrible result of a binary file not even close to the one I need. Commented Aug 8, 2014 at 19:19

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I am having trouble now when adding this code to my Forms Application. When I tested this in my simple Console app it worked beautifully. Now I moved this code into an Event Handler in my Forms application, and it is producing a terrible result of a binary file not even close to the one I need.
Well without any more information about the input, expected output or actual output, it's hard to know what's wrong. I suggest you ask a new question with all the relevant details.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.