c#学习笔记
c#的一些查博客学习记录
这里主要记录一下一些简单的语法点,因为c#并不是主要使用的语言,所以来回的查一些接口是比较烦的。
之后会持续的更新一些有效的方法。
创建数组
//一维数组
int[] array = new int[5];
//二维数组
int[][] array = new int[5][2];
c#中内存相关
清空数组内存
//类似于c中memset
byte[] test = new byte[65536];
Array.Clear(test,0,test.Length);
byte数组类型转换
//错误写法
byte[] buffer = new byte[1000];
short[] samples = (short[])buffer; // compile error!
下面是一些正确写法
BitConverter
//to int16
byte[] buffer = ...;
for(int n = 0; n < buffer.Length; n+=2)
{
short sample = BitConverter.ToInt16(buffer, n);
}
//to int32
byte[] buffer = ...;
for(int n = 0; n < buffer.Length; n+=2)
{
short sample = BitConverter.ToInt16(buffer, n);
}
//to float
byte[] buffer = ...;
for(int n = 0; n < buffer.Length; n+=2)
{
short sample = BitConverter.ToSingle(buffer, n);
}
Bit Manipulation
//这种没用过,遇到实际场景后会再深究
byte[] buffer = ...;
for (int n = 0; n < buffer.Length; n+=2)
{
short sample = (short)(buffer[n] | buffer[n+1] << 8);
}
Buffer.BlockCopy
//这不错的方法,但是不断的new会浪费大量内存,使用时注意技巧
byte[] buffer = ...;
short[] samples = new short[buffer.Length];
Buffer.BlockCopy(buffer,0,samples,0,buffer.Length);
WaveBuffer
//同样没用过的方法
byte[] buffer = ...;
var waveBuffer = new WaveBuffer(buffer);
// now you can access the samples using waveBuffer.ShortBuffer, e.g.:
var sample = waveBuffer.ShortBuffer[sampleIndex];
Unsafe Code
//性能最好,但是出错概率最大,用的时候需要注意
byte[] buffer = ...;
unsafe
{
fixed (byte* pBuffer = buffer)
{
short* pSample = (short*)buffer;
// now we can access samples via pSample e.g.:
var sample = pSample[sampleIndex];
}
}
参考博客地址:https://markheath.net/post/how-to-convert-byte-to-short-or-float