using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 全自动水压检测仪
{
public class DataChange
{
///
/// ushort转为float类型
///
///
///
/// float型数据
public float UshortToFloat(ushort P1, ushort P2)
{
int intSign, intSignRest, intExponent, intExponentRest;
float faResult, faDigit;
intSign = P1 / 32768;
intSignRest = P1 % 32768;
intExponent = intSignRest / 128;
intExponentRest = intSignRest % 128;
faDigit = (float)(intExponentRest * 65536 + P2) / 8388608;
faResult = (float)Math.Pow(-1, intSign) * (float)Math.Pow(2, intExponent - 127) * (faDigit + 1);
return faResult;
}
///
/// ushort转为int类型
///
///
///
/// 返回int型数据
public int UshortToInt1(ushort u1, ushort u2)
{
ushort[] maidong = new ushort[2] { u1, u2 };
byte[] bytes = new byte[maidong.Length * 2];
Buffer.BlockCopy(maidong, 0, bytes, 0, bytes.Length);
int result = BitConverter.ToInt32(bytes, 0);
// 将字节数组转换为32位无符号整数
return result;
}
///
/// Float转为Ushort数组发送
///
///
/// 返回ushort数组
public ushort[] SplitFloatToUShortArray(float value)
{
byte[] floatBytes = BitConverter.GetBytes(value);
ushort[] ushortArray = new ushort[floatBytes.Length / 2];
for (int i = 0, j = 0; i < floatBytes.Length; i += 2, j++)
{
ushortArray[j] = BitConverter.ToUInt16(floatBytes, i);
}
return ushortArray;
}
///
/// Int转为ushort数组发送
///
///
/// 返回ushort数组
public ushort[] intToushorts(int res)
{
ushort ust1 = (ushort)(res >> 16);
ushort ust2 = (ushort)res;
return new ushort[] { ust2, ust1 };
}
}
}