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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值