我有一个音频数据数组,它是很多由字节数组表示的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
发布评论