一、浮点数 Float 转为 ushort[]数组
// 将浮点数转换为两个16位的寄存器值(IEEE 754格式)
public static ushort[] FloatToRegisters(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
ushort high = BitConverter.ToUInt16(bytes, 0);
ushort low = BitConverter.ToUInt16(bytes, 2);
//这里的高低位,根据PLC情况,一般是低位在前,高位在后
return new ushort[] { low , high };
}
二、 ushort[]数组 转为 浮点数 Float
// 假设我们有两个ushort值,它们代表一个浮点数的二进制表示
//ushort high = 0x4049; // 浮点数的高16位
//ushort low = 0x0FDB; // 浮点数的低16位
// 将两个ushort值合并为一个32位的整数
//uint combined = (uint)high << 16 | (uint)low;
// 将32位整数转换为float
//float floatValue = BitConverter.ToSingle(BitConverter.GetBytes(combined), 0);
public static float UshortToFloat(ushort low,ushort high)
{
// 将两个ushort值合并为一个32位的整数
uint combined = (uint)high << 16 | (uint)low;
// 将32位整数转换为float
return float floatValue = BitConverter.ToSingle(BitConverter.GetBytes(combined), 0);
}
三、将 Double 类型转换成 ushort[]
public static ushort[] DoubleToRegisters(double value)
{
// 将double转换为字节数组
byte[] bytes = BitConverter.GetBytes(value);
// 将字节数组转换为ushort数组(注意字节序问题,这里假设是小端序)
ushort[] registers = new ushort[4];
for (int i = 0; i < bytes.Length; i += 2)
{
registers[i / 2] = BitConverter.ToUInt16(bytes, i);
}
return registers;
}
四、将ushort[] 转换成 double
public static double ToDouble(ushort[] u)
{
//将四个ushort值合并为一个64位的ulong
ulong combined = ((ulong)u[0]<< 48) | ((ulong)u[1]<< 32) | ((ulong)u[2] << 16) | u[3];
// 将64位的ulong转换为double
return double doubleValue = BitConverter.ToDouble(BitConverter.GetBytes(combined), 0);
}