在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
在做上位机的项目的时候,一般会把数字转成十六进制再发送给下位机。一般会用1个byte,2个byte,4个byte来表示对应的十进制数。相关的转换可以用下面的方法: 负数转成1byte,2byte,4 byte ?Convert.ToSByte("-50").ToString("X")
?Convert.ToInt32("-30000").ToString("X8");
var a = Convert.ToInt16("-100").ToString("X"); ushort Location = -10000;
16进制数据转负数。 string strLocation = Convert.ToInt32(Location).ToString("X8"); 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
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论