开发者

How Write a List<int> to binary file (4 bytes long)?

I need to write a List of ints to a binary file of 4 bytes in length, so, I need to make sure that the binary file is correct, and I do the following:

using (FileStream fileStream = new FileStream(binaryFileName, FileMode.Create)) // desti开发者_运维问答ny file directory.
{
  using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
  {
    for (int i = 0; i < frameCodes.Count; i++)
    {
      binaryWriter.Write(frameCodes[i]);
      binaryWriter.Write(4);
    }
    binaryWriter.Close();
  }
}

at this line: binaryWriter.Write(4); I give the size, is that correct?


at this line "binaryWriter.Write(4);" I give the size, that's correct??

No, it's not correct. The line binaryWriter.Write(4); will write the integer 4 into the stream (e.g. something like 00000000 00000000 00000000 00000100).

This line is correct: binaryWriter.Write(frameCodes[i]);. It writes the integer frameCodes[i] into the stream. Since an integer requires 4 bytes, exactly 4 bytes will be written.

Of course, if your list contains X entries, then the resulting file will be of size 4*X.


AS PER MSDN

These two might help you. I know its not close to answer but will help you in getting the concept

using System;

public class Example
{
   public static void Main()
   {
      int value = -16;
      Byte[] bytes = BitConverter.GetBytes(value); 

      // Convert bytes back to Int32.
      int intValue = BitConverter.ToInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}", 
                        value, intValue, 
                        value.Equals(intValue) ? "Round-trips" : "Does not round-trip");
      // Convert bytes to UInt32.
      uint uintValue = BitConverter.ToUInt32(bytes, 0);
      Console.WriteLine("{0} = {1}: {2}", value, uintValue, 
                        value.Equals(uintValue) ? "Round-trips" : "Does not round-trip");
   }
}

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜