在做上位機的項目的時候,一般會把數字轉成十六進制再發送給下位機。一般會用1個byte,2個byte,4個byte來表示對應的十進制數。相關的轉換可以用下面的方法:
負數轉成1byte,2byte,4 byte
?Convert.ToSByte("-50").ToString("X")
"CE"
?Convert.ToInt16("-50").ToString("X");
"FFCE"
?Convert.ToInt32("-50").ToString("X");
"FFFFFFCE"
?Convert.ToInt16("-30000").ToString("X");
"8AD0"
?Convert.ToInt32("-30000").ToString("X8");
"FFFF8AD0"
?Convert.ToInt32("-30000").ToString("X8");
"FFFF8AD0"
var a = Convert.ToInt16("-100").ToString("X");
var b = Convert.ToInt64("-9999000000").ToString("X32");
ushort us = Convert.ToUInt16(("0x" + a), 16);
ushort Location = -10000;
16進制數據轉負數。
string strLocation = Convert.ToInt32(Location).ToString("X8");
double dLocation = Convert.ToDouble( Convert.ToInt16(strLocation.Substring(4, 4), 16)) / Convert.ToDouble(1000);
Convert.ToDouble((dLocation).ToString("0.00"));
1 /// <summary> 2 /// 3 /// </summary> 4 /// <param name="value">數據</param> 5 /// <param name="byteOrder">類型1234/3412</param> 6 /// <returns></returns> 7 private static float ByteArrayToFloat(ushort[] value, int byteOrder) 8 { 9 byte[] bytes = null; 10 switch (byteOrder) 11 { 12 case 0: //1234 opto22 13 bytes = new byte[] { 14 (byte)((value[0] >> 8) & 0xff), 15 (byte)((value[0] >> 0) & 0xff), 16 (byte)((value[1] >> 8) & 0xff), 17 (byte)((value[1] >> 0) & 0xff), 18 }; 19 if (BitConverter.IsLittleEndian) 20 Array.Reverse(bytes); 21 return BitConverter.ToSingle(bytes, 0); 22 case 1: //3412 selec 23 bytes = new byte[] { 24 (byte)((value[1] >> 8) & 0xff), 25 (byte)((value[1] >> 0) & 0xff), 26 (byte)((value[0] >> 8) & 0xff), 27 (byte)((value[0] >> 0) & 0xff), 28 }; 29 if (BitConverter.IsLittleEndian) 30 Array.Reverse(bytes); 31 return BitConverter.ToSingle(bytes, 0); 32 } 33 throw new ArgumentException(); 34 }
#region 進制轉BOOL /// <summary> /// /// </summary> /// <param name="packet">數值</param> /// <param name="offset">固定值3</param> /// <param name="count">數據長度</param> /// <returns></returns> public static bool[] DecodeBools(byte[] packet, int offset, ushort count) { var bools = new bool[count]; var bytes = BytesForBools(count); for (var i = 0; i < bytes; i++) { var bits = count >= 8 ? 8 : count % 8; var b = packet[offset + i]; ByteToBools(b, bools, bools.Length - count, bits); count -= (ushort)bits; } return bools; } private static void ByteToBools(byte b, bool[] bools, int offset, int count) { for (int i = 0; i < count; i++) bools[offset + i] = ((b >> i) & 0x01) == 1; } public static byte BytesForBools(int count) { return (byte)(count == 0 ? 0 : (count - 1) / 8 + 1); } #endregion
#region 高低位數據轉換 public static byte High(int value) { return (byte)((value >> 8) & 0xff); } public static byte Low(int value) { return (byte)((value >> 0) & 0xff); } #endregion