如何解决如何将List <int>写入二进制文件长4个字节?
| 我需要将一个整数列表写入长度为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);
我给的大小,对吗?
解决方法
在这一行“ binaryWriter.Write(4); \”我给出大小,这是正确的吗?
不,这是不正确的。行
binaryWriter.Write(4);
将整数4
写入流中(例如00000000 00000000 00000000 00000100
之类)。
这行是正确的:binaryWriter.Write(frameCodes[i]);
。它将整数“ 6”写入流中。由于整数需要4个字节,因此将精确地写入4个字节。
当然,如果您的列表包含X个条目,则结果文件的大小将为4 * X。
,作为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,uintValue,value.Equals(uintValue) ? \"Round-trips\" : \"Does not round-trip\");
}
}
byte[] bytes = { 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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。