将字节数组转换为 Short 数组而不复制数据

发布于 2024-11-07 07:13:31 字数 441 浏览 0 评论 0原文

我有一个字节数组,它们实际上是来自声卡的 16 位样本。所以1000字节实际上代表500个Short(16位值)。

目前我正在像这样转换它们:

byte [] inputData = new byte[1000];
short [] convertedData = new short[500];
Buffer.BlockCopy(inputData, 0, convertedData , 0, 1000);

它工作正常并且速度非常快,因为它是低级字节副本。

但是有没有办法在没有副本的情况下做到这一点?即告诉 C# 将这个内存区域视为 500 个 Shorts 的数组而不是 1000 个字节?我知道在 C/C++ 中我可以直接转换指针,它就可以工作。

此副本发生在一个紧密的循环中,每秒最多 5000 次,因此如果我可以删除该副本,那将是值得的。

I have an array of bytes that are actually 16-bit samples from a sound card. So 1000 bytes actually represents 500 Short (16-bit values).

Currently I'm converting them like this:

byte [] inputData = new byte[1000];
short [] convertedData = new short[500];
Buffer.BlockCopy(inputData, 0, convertedData , 0, 1000);

It works fine and it's pretty quick as it's a low-level byte copy.

However is there a way to do it without the copy? i.e. tell C# to treat this area of memory as an array of 500 shorts instead of 1000 bytes? I know that in C/C++ I could just cast the pointer and it would work.

This copy happens in a tight loop, up to 5000 times a second, so if I can remove the copy it would be worthwhile.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南城追梦 2024-11-14 07:13:31

StructLayout 允许您控制类或结构中数据字段的物理布局。它通常在与需要特定布局的数据的非托管代码交互时使用。

尝试一下:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public short[] Shorts;
}

static void Main(string[] args)
{
    var union = new UnionArray() {Bytes = new byte[1024]};

    foreach (short s in union.Shorts)
    {
        Console.WriteLine(s);
    }
}

StructLayout lets you control the physical layout of the data fields in a class or structure. It is typically used when interfacing with unmanaged code which expects the data in a specific layout.

Give this a try:

[StructLayout(LayoutKind.Explicit)]
struct UnionArray
{
    [FieldOffset(0)]
    public Byte[] Bytes;

    [FieldOffset(0)]
    public short[] Shorts;
}

static void Main(string[] args)
{
    var union = new UnionArray() {Bytes = new byte[1024]};

    foreach (short s in union.Shorts)
    {
        Console.WriteLine(s);
    }
}
分開簡單 2024-11-14 07:13:31

也许是 C 语言 C# 模拟 union 就可以解决问题。

Perhaps a C# analog of the C-language union would do the trick.

听不够的曲调 2024-11-14 07:13:31
bytes[] inputData = Array.ConvertAll<short, bytes>(bytes, delegate(short[] convertedData) { return short.Parse(convertedData); } );

类似的事情,我没有检查,但也许这会对你有所帮助:)

bytes[] inputData = Array.ConvertAll<short, bytes>(bytes, delegate(short[] convertedData) { return short.Parse(convertedData); } );

something like that, i didnt check, but maybe that'll help you out :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文