Convert numbers to hexadecimal. The premise is that what you enter must be numbers and nothing else.
private string StringToHexString(string s)//数字转换16进制
{
long Num = Convert.ToInt32(s);//防止溢出
string str = Convert.ToString(Num, 16);
string Msg = "0x" + (str.Length == 1 ? "0" + str : str);//转换成指定格式
return Msg;
}
String conversion to hexadecimal, here we refer to many other people's methods. You can use StringBuilder, or you can convert it one by one and then store it . It depends on personal preference.
public string ToStrFromByte(byte[] byteDatas)//字符串转化16进制
{
string Msg = "";
//StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteDatas.Length; i++)
{
string str = Convert.ToString(byteDatas[i], 16);
Msg = "0x" + (str.Length == 1 ? "0" + str : str);//转换成16进制格式
//builder.Append(string.Format("{0:X2} ", byteDatas[i]));
}
return Msg;
}
The final effect is achieved (taking the serial port program I learned to make as an example):