gpt4 book ai didi

c# - C# 的 ByteArray 类

转载 作者:行者123 更新时间:2023-11-30 14:55:19 25 4
gpt4 key购买 nike

我正在尝试将函数从 ActionScript 3 转换为 C# .NET。

我遇到的问题是如何在 C# 中正确使用 ByteArrays。在 As3 中有一个特定的类,它已经具有我需要的大部分功能,但在 C# 中似乎不存在那种东西,我无法理解它。

这是 As3 函数:

private function createBlock(type:uint, tag:uint,data:ByteArray):ByteArray
{
var ba:ByteArray = new ByteArray();
ba.endian = Endian.LITTLE_ENDIAN;
ba.writeUnsignedInt(data.length+16);
ba.writeUnsignedInt(0x00);
ba.writeUnsignedInt(type);
ba.writeUnsignedInt(tag);
data.position = 0;
ba.writeBytes(data);
ba.position = 0;

return ba;
}

但据我所知,在 C# 中我必须使用字节类型的普通数组,如下所示

byte[] ba = new byte[length];

现在,我查看了编码类、BinaryWriter 和 BinaryFormatter 类,并研究了是否有人为 ByteArrays 创建了一个类,但没有成功。

有人可以在正确的方向轻推我吗?

最佳答案

您应该能够使用 MemoryStreamBinaryWriter 的组合来做到这一点:

public static byte[] CreateBlock(uint type, uint tag, byte[] data)
{
using (var memory = new MemoryStream())
{
// We want 'BinaryWriter' to leave 'memory' open, so we need to specify false for the third
// constructor parameter. That means we need to also specify the second parameter, the encoding.
// The default encoding is UTF8, so we specify that here.

var defaultEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier:false, throwOnInvalidBytes:true);

using (var writer = new BinaryWriter(memory, defaultEncoding, leaveOpen:true))
{
// There is no Endian - things are always little-endian.

writer.Write((uint)data.Length+16);
writer.Write((uint)0x00);
writer.Write(type);
writer.Write(data);
}

// Note that we must close or flush 'writer' before accessing 'memory', otherwise the bytes written
// to it may not have been transferred to 'memory'.

return memory.ToArray();
}
}

但是,请注意 BinaryWriter 始终使用小端格式。如果你需要控制这个,你可以使用Jon Skeet's EndianBinaryWriter反而。

作为这种方法的替代方法,您可以传递流而不是字节数组(可能使用 MemoryStream 来实现),但是您需要注意生命周期管理,即谁将完成后关闭/处理流? (您可能可以不用费心关闭/处置内存流,因为它不使用非托管资源,但这并不是完全令人满意的 IMO。)

关于c# - C# 的 ByteArray 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25638856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com