using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Aitex.Core.Util
{
public static class Converter
{
/////
///// Unit converter from physical to logical in linear formula
/////
/////
public static double Phy2Logic(double physicalValue, double logicalMin, double logicalMax, double physicalMin, double physicalMax)
{
var ret = (logicalMax - logicalMin) * (physicalValue - physicalMin) / (physicalMax - physicalMin) + logicalMin;
//if (ret < logicalMin) ret = logicalMin;
//if (ret > logicalMax) ret = logicalMax;
if (double.IsNaN(ret)) throw new DivideByZeroException("Phy2Logic除0操作");
return ret;
}
/////
///// Unit converter from logical to physical in linear formula
/////
/////
public static double Logic2Phy(double logicalValue, double logicalMin, double logicalMax, double physicalMin, double physicalMax)
{
var ret = (physicalMax - physicalMin) * (logicalValue - logicalMin) / (logicalMax - logicalMin) + physicalMin;
if (ret < physicalMin) ret = physicalMin;
if (ret > physicalMax) ret = physicalMax;
if (double.IsNaN(ret))
throw new DivideByZeroException("Logic2Phy除0操作");
return ret;
}
///
/// 只按占用的字节转换,不检查范围
///
///
///
///
public static float TwoUInt16ToFloat(UInt16 high, UInt16 low)
{
Int32 sum = (high << 16) + (low & 0xFFFF);
byte[] bs = BitConverter.GetBytes(sum);
return BitConverter.ToSingle(bs, 0);
}
public static int TwoInt16ToInt32(Int16 high, Int16 low)
{
UInt32 tmp = (ushort)low + (UInt32)(((ushort)high) << 16);
return tmp > Int32.MaxValue ? (int)((~tmp + 1) * -1) : (int)tmp;////unsigned to signed
}
public static float TwoInt16ToFloat(Int16 high, Int16 low)
{
Int32 sum = (high << 16) + (low & 0xFFFF);
byte[] bs = BitConverter.GetBytes(sum);
return BitConverter.ToSingle(bs, 0);
}
public static bool[] GetboolArrayByByte(byte byt)
{
bool[] ret = new bool[8];
ret[0] = ((byte)(byt & 0x01) == 0x01);
ret[1] = ((byte)(byt>>1 & 0x01) == 0x01);
ret[2] = ((byte)(byt>>2 & 0x01) == 0x01);
ret[3] = ((byte)(byt>>3 & 0x01) == 0x01);
ret[4] = ((byte)(byt>>4 & 0x01) == 0x01);
ret[5] = ((byte)(byt>>5 & 0x01) == 0x01);
ret[6] = ((byte)(byt>>6 & 0x01) == 0x01);
ret[7] = ((byte)(byt>>7 & 0x01) == 0x01);
return ret;
}
public static byte GetByteValueByBoolArray(bool[] byt)
{
byte value = 0;
for(int i = 0; i < byt.Length; i++)
{
if (byt[i])
{
value += (byte)(1 << i);
}
}
return value;
}
}
}