using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StressClient.Common { public class StrHexHelper { // 字符串转16进制字符串 AB-->4142 public static string StrToHexStr(string str, Encoding encode) { byte[] b = encode.GetBytes(str); string result = string.Empty; foreach (var t in b) { result += Convert.ToString(t, 16); } return result; } // 将16进制字符串转换到byte[] public static byte[] HexStrToArray(string str) { int count = str.Length / 2; byte[] b = new byte[count]; for (int i = 0; i < count; i++) { string val = "0x" + str.Substring(i * 2, 2); b[i] = Convert.ToByte(val, 16); // '0x41'->65 } return b; } public static string do_CRC(byte[] data) { uint crc = 0xFFFF; foreach (var pos in data) { crc = (crc >> 8) ^ pos; for (int i = 0; i < 8; i++) { var check = (byte)(crc & 0x0001); crc >>= 1; if (check == 0x0001) crc ^= 0xA001; } } //string ret_str = Convert.ToString(crc, 16); string ret_str = crc.ToString("X4"); ; return ret_str.ToUpper(); } public static string do_CRC16(byte[] data) { byte[] returnVal = new byte[2]; byte CRC16Lo, CRC16Hi, CL, CH, SaveHi, SaveLo; int i, Flag; CRC16Lo = 0xFF; CRC16Hi = 0xFF; CL = 0x86; CH = 0x68; for (i = 0; i < data.Length; i++) { CRC16Lo = (byte)(CRC16Lo ^ data[i]);//每一个数据与CRC寄存器进行异或 for (Flag = 0; Flag <= 7; Flag++) { SaveHi = CRC16Hi; SaveLo = CRC16Lo; CRC16Hi = (byte)(CRC16Hi >> 1);//高位右移一位 CRC16Lo = (byte)(CRC16Lo >> 1);//低位右移一位 if ((SaveHi & 0x01) == 0x01)//如果高位字节最后一位为 { CRC16Lo = (byte)(CRC16Lo | 0x80);//则低位字节右移后前面补 否则自动补0 } if ((SaveLo & 0x01) == 0x01)//如果LSB为1,则与多项式码进行异或 { CRC16Hi = (byte)(CRC16Hi ^ CH); CRC16Lo = (byte)(CRC16Lo ^ CL); } } } returnVal[0] = CRC16Hi;//CRC高位 returnVal[1] = CRC16Lo;//CRC低位 return Encoding.UTF8.GetString(returnVal); } } public class Helper { public static decimal GetRan(int val, int diff, decimal k = 1) { if (k <= 0) return 0; System.Threading.Thread.Sleep(new Random().Next(10, 30)); var ran = Convert.ToDecimal(new Random(DateTime.Now.Millisecond).Next(val - diff, val + diff)) / k; return ran; } } }