首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将List<int>写入二进制文件(4字节长)?

如何将List<int>写入二进制文件(4字节长)?
EN

Stack Overflow用户
提问于 2011-04-15 14:10:55
回答 2查看 4.6K关注 0票数 2

我需要将ints列表写入长度为4字节的二进制文件,因此,我需要确保二进制文件是正确的,并执行以下操作:

代码语言:javascript
运行
复制
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);我给出了尺寸,对吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-04-15 14:15:20

在这一行"binaryWriter.Write(4);“我给出了大小,对吗??

不,这不对。行binaryWriter.Write(4);将整数4写入流(例如,类似于00000000 00000000 00000000 00000100)。

这一行是正确的:binaryWriter.Write(frameCodes[i]);。它将整数frameCodes[i]写入流中。因为一个整数需要4个字节,所以精确的4个字节将被写入。

当然,如果列表中包含X项,则生成的文件大小为4*X。

票数 2
EN

Stack Overflow用户

发布于 2011-04-15 14:17:38

根据MSDN

这两个人可能会帮你的。我知道这不太接近答案,但会帮助你理解这个概念。

代码语言:javascript
运行
复制
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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5678011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档