1.字符串类型浮点数转float类型
- string strNumber = "71.068";
- float floatNumber =float.Parse(strNumber); //输出floatNumber =71.068
2.浮点数转4个字节(float类型),double默认转8个字节
- float floatNumber = 71.068f;
- byte[] result = BitConverter.GetBytes(floatNumber);//float浮点数默认转为4个字节,double默认转8个字节
- //输出结果:D1 22 8E 42
- Array.Reverse(result); //数组元素翻转 42 8E 22 D1
3.int转4个字节 ,short默认转2个字节
- byte[] result2 = BitConverter.GetBytes((int)23.5); //将23.5转为int即23
- Array.Reverse(result2); //输出结果 00 00 00 17
4. list集合转数组(一维)
- List<byte> listBytes1 = new List<byte>();
- listBytes1.Add(0x01);
- listBytes1.Add(0x02);
- listBytes1.Add(0x03);
- byte[] result3 = listBytes1.ToArray(); //result3存放的为0x01,0x02,0x03
5.list集合转数组(二维)
- List<byte[]> listBytes1 = new List<byte[]>();
- float floatNumber = 71.068f;
- byte[] result = BitConverter.GetBytes(floatNumber);//float浮点数默认转为4个字节,double默认转8个字节
- //输出结果:D1 22 8E 42
- Array.Reverse(result); //数组元素翻转 42 8E 22 D1
- listBytes1.Add(result); //添加到集合中去
- byte[] result2 = BitConverter.GetBytes((int)23.5);
- Array.Reverse(result2); //输出结果 00 00 00 17
- listBytes1.Add(result2); //添加到集合中去
- byte[] result3 = listBytes1.SelectMany(bytes => bytes).ToArray(); //集合转数组
- //输出结果:42 8E 22 D1 00 00 00 17