2011-04-15 51 views
2

我需要INTS的名单写的4个字节长的二进制文件,所以,我需要确保该二进制文件是正确的,我做了以下内容:如何将一个列表<int>写入二进制文件(4个字节长)?

using (FileStream fileStream = new FileStream(binaryFileName, FileMode.Create)) // destiny 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(); 
    } 
} 

在这一行:binaryWriter.Write(4);我给大小,是否正确?

回答

2

在这一行“binaryWriter.Write(4);”我给大小,这是正确的?

不,这是不正确的。行binaryWriter.Write(4);将把整数4写入流(例如类似00000000 00000000 00000000 00000100)。

此线路是正确的:binaryWriter.Write(frameCodes[i]);。它将整数frameCodes[i]写入流中。由于一个整数需要4个字节,所以正好会写入4个字节。

当然,如果你的列表包含X条目,那么结果文件的大小将是4 * X。

1

根据MSDN

这两个可能会帮助你。我知道它不会接近答案,但会帮助你获得概念

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); 
相关问题