操控平台后端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
1.2 KiB

4 months ago
namespace Bodk.Extensions.Modbus;
public static class ConvertExtensions
{
public static float[] ConvertToFloat(this ushort[] ushortArray)
{
if (ushortArray == null || ushortArray.Length % 2 != 0)
{
throw new ArgumentException("The ushort array must have an even length.");
}
float[] floatArray = new float[ushortArray.Length / 2];
for (int i = 0; i < floatArray.Length; i++)
{
// Get two consecutive ushort values
ushort low = ushortArray[2 * i];
ushort high = ushortArray[2 * i + 1];
// Combine the two ushort values into a single uint (32-bit integer)
uint combined = ((uint)high << 16) | low;
// Convert the uint to a float
floatArray[i] = BitConverter.ToSingle(BitConverter.GetBytes(combined), 0);
}
return floatArray;
}
public static ushort[] ConvertToUShort(this float value)
{
byte[] byteArray = BitConverter.GetBytes(value);
ushort[] ushortArray = new ushort[2];
ushortArray[0] = BitConverter.ToUInt16(byteArray, 0);
ushortArray[1] = BitConverter.ToUInt16(byteArray, 2);
return ushortArray;
}
}