/// <summary>
/// 将一个byte数组转换成16进制字符串
/// </summary>
/// <param name="data">byte数组</param>
/// <returns>格式化的16进制字符串</returns>
public static string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
}
return sb.ToString().ToUpper();
}
//累加和校验【每字节相加(16进)取后末两位】
public byte GetVerifyCodeByte(byte[] bytes)
{
int result = 0;
foreach (byte b in bytes)
{
result += b;
}
return (byte)(result % 256);
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] StrToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/***字节数组转换成ASII-开始***/
public void changeasii(){
//定义4字节的数组
byte[] verbytearrc = new byte[4];
//转换结果
String asii_vet_1 = Encoding.ASCII.GetString(verbytearrc);
/***字节数组转换成ASII-结束***/
/****IEEE-754 浮点数 转byte数组高位在前 -开始***/
float f = 525.0f;
//将浮点数转换成数组
byte[] b = BitConverter.GetBytes(f);
//浮点转换为四字节数组
byte[] bs = BitConverter.GetBytes(f);
//排列高位在前
bs[1] bs[0] bs[3] bs[2]
一个字节:00
}
/****IEEE-754 浮点数 转byte数组高位在前 -结束***/
/*********将16进制byte转换成浮点数格式***********/
public void changeHex2Float(){
//转换数组-高位在前
byte[] bbytearrc = new byte[4];
bbytearrc[0] = verbytearr[2];
bbytearrc[1] = verbytearr[3];
bbytearrc[2] = verbytearr[0];
bbytearrc[3] = verbytearr[1];
//转换十六进制的字符串
String rev_strc = ByteArrayToHexString(bbytearrc);
//字符串转16进制32位无符号整数
uint x = Convert.ToUInt32(rev_strc, 16);
float kval = BitConverter.ToSingle(BitConverter.GetBytes(x), 0);//IEEE754 字节转换float
}
/***********将16进制byte转换成浮点数格式*********/
/**********************************************/
/***延时执行***/
public void depley(){
ThreadPool.QueueUserWorkItem(state =>
{
//延迟1秒执行
Thread.Sleep(1000);
BeginInvoke(new Action(() =>
{
if (this.clear_checkbox.Checked)
{
//清除所有文本
this.command_rtx.Clear();
//初始化选中状态
this.clear_checkbox.Checked = false;
}
}));
});
}
C#-串口-模拟量采集软件-4-用到的公用方法
于 2022-04-25 14:14:00 首次发布