求和用C#中的字节数组表示的Int32

编程入门 行业动态 更新时间:2024-10-27 00:31:29
本文介绍了求和用C#中的字节数组表示的Int32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个音频数据数组,它是很多由字节数组表示的Int32数字(每个4字节元素表示一个Int32),并且我想对数据进行一些处理(例如,对每个数据加10 Int32)。

I have an array of audio data, which is a lot of Int32 numbers represented by array of bytes (each 4 byte element represents an Int32) and i want to do some manipulation on the data (for example, add 10 to each Int32).

我将字节转换为Int32,进行操作并将其转换回字节,如本例所示:

I converted the bytes to Int32, do the manipulation and convert it back to bytes as in this example:

//byte[] buffer; for (int i=0; i<buffer.Length; i+=4) { Int32 temp0 = BitConverter.ToInt32(buffer, i); temp0 += 10; byte[] temp1 = BitConverter.GetBytes(temp0); for (int j=0;j<4;j++) { buffer[i + j] = temp1[j]; } }

但我想知道是否有更好的选择

But I would like to know if there is a better way to do such manipulation.

推荐答案

您可以检查。NET参考源,以获取有关如何从/向大端转换的指针(笑)。

You can check the .NET Reference Source for pointers (grin) on how to convert from/to big endian.

class intFromBigEndianByteArray { public byte[] b; public int this[int i] { get { i <<= 2; // i *= 4; // optional return (int)b[i] << 24 | (int)b[i + 1] << 16 | (int)b[i + 2] << 8 | b[i + 3]; } set { i <<= 2; // i *= 4; // optional b[i ] = (byte)(value >> 24); b[i + 1] = (byte)(value >> 16); b[i + 2] = (byte)(value >> 8); b[i + 3] = (byte)value; } } }

并使用示例:

byte[] buffer = { 127, 255, 255, 255, 255, 255, 255, 255 };//big endian { int.MaxValue, -1 } //bool check = BitConverter.IsLittleEndian; // true //int test = BitConverter.ToInt32(buffer, 0); // -129 (incorrect because little endian) var fakeIntBuffer = new intFromBigEndianByteArray() { b = buffer }; fakeIntBuffer[0] += 2; // { 128, 0, 0, 1 } = big endian int.MinValue - 1 fakeIntBuffer[1] += 2; // { 0, 0, 0, 1 } = big endian 1 Debug.Print(string.Join(", ", buffer)); // "128, 0, 0, 0, 1, 0, 0, 1"

更好您可以查看并行处理和SIMD指令的性能-在C#中使用SSE 为了获得更好的性能,您可以查看通过c#使用GPU

For better performance you can look into parallel processing and SIMD instructions - Using SSE in C# For even better performance, you can look into Utilizing the GPU with c#

更多推荐

求和用C#中的字节数组表示的Int32

本文发布于:2023-11-06 04:12:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字节

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!