C# 字节数组与INT16,float,double之间相互转换,字符数组与字符串相互转换,

一.字符数组与字符串相互转换

1.1 代码是将4个字符拼接位字符串

如果你已经有了4个字节大小的字符串,第一个参数可以直接传buff[4],由于博主这里只是截取一部分数据所以是如下操作。

string temp_s=new string(new char[4] { (char)buff[0], (char)buff[1], (char)buff[2], (char)buff[3] });

1.2 字符串拆为字符数组

Byte[]  bytes_s = BitConverter.GetBytes(temp_s);

二.2个字节数据与INT16类型相互转换

2.1 2字节转化为INT16

如果你已经有了2个字节大小的数组,第一个参数可以直接传buff,由于博主这里是buff中的任意2个数据所以是如下操作。

 Int16 temp_16=(BitConverter.ToInt16(new byte[2] { buff[2], buff[3] }, 0);

2.2 INT16转为2字节数组

Byte[] bytes_16 = BitConverter.GetBytes(temp_16);

三. 4字节数组与float类型相互转化

3.1 4个字节转为float

float temp_f=(BitConverter.ToSingle(new byte[4] { buff[1], buff[2],buff[3],buff[4] }, 0);

3.2 float转为4字节

Byte[] bytes_f = BitConverter.GetBytes(temp_f);

四. 8字节数组和double之间相互转化

4.1 8字节数据转double

double temp_d=(BitConverter.ToDouble(bytes_d[8], 0);

4.2 double 转为8字节数据

Byte[] bytes_d= BitConverter.GetBytes(temp_d);

你可能感兴趣的:(C#,winform,算法,c#,visual,studio)