【问题标题】:How to read UInt32 numbers of bytes with binary reader?如何使用二进制阅读器读取 UInt32 字节数?
【发布时间】:2014-01-20 07:28:59
【问题描述】:

我需要我的代码来做这样的事情 - 在代码中的某处 num 获取一个值,然后我想从文件中读取,因为字节是数字 num

例如:如果 num 为 39382,我需要读取 39382 个字节并将它们放入 byte[] 缓冲区;

在我有这样的事情之前:

ushort num = 0;
//....  num get some value;
byte[] buffer = bRead.ReadBytes(num);

现在我必须将其更改为 numUInt32,但随后 ReadBytes 不起作用(因为它需要 int32)。 'num' 可能超过 int32。我是这样修复的:

byte[] buffer = new byte[num];
for (int j = 0; j < num; j++)
{
    buffer[j] = bRead.ReadByte();
}

它有效,但我想知道这是最好的方法吗?还是有别的?

【问题讨论】:

  • 警告:分配 >2GB 数组仅适用于 gcAllowVeryLargeObjects 设置为 true 的 .NET 4.5 64 位。您可能希望使用 FileStream 或同等名称。
  • 这就是我想用更好的改变它的原因之一。

标签: c# binaryreader uint32


【解决方案1】:

如果您确定 num 不会超过 int32 最大值,您可以使用以下内容:

UInt32 num = 0;
//....  num get some value;
bRead.ReadBytes(checked((int)num));

如果 num 超出有符号的 32 位最大值,这将引发 OverflowException。

【讨论】:

  • 如果我知道它不会超过 int32 的最大值,我将把它设为 int。
【解决方案2】:

你可以使用:

public static ushort ToUInt32(
    byte[] value,
    int startIndex
)

您指定源数组和编码数字开始的位置。如果您的字节数组包含单个数字,startIndex 将为 0,并且长度必须至少为 4。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多