C#串口通讯中常用的16进制的字节转换
2021-04-15 12:27
标签:AC source char tst 一个 numbers bst over lob //二进制转十进制 //十进制转二进制 /// //不满8位就补零 // { } return covertHexByte; /// return outputStr; /// /// return outputStr; C#串口通讯中常用的16进制的字节转换 标签:AC source char tst 一个 numbers bst over lob 原文地址:https://www.cnblogs.com/Qxian/p/8698768.html1.对于通讯协议的十六进制数值进行简单转换
Console.WriteLine("二进制 111101 的十进制表示: "+Convert.ToInt32("111101", 2));
//八进制转十进制
Console.WriteLine("八进制 44 的十进制表示: "+Convert.ToInt32("44", 8));
//十六进制转十进制
Console.WriteLine("十六进制 CC的十进制表示: "+Convert.ToInt32("CC", 16)); /*比较常用*/
Console.WriteLine("十进制166的二进制表示: "+Convert.ToString(166, 2));
//十进制转八进制
Console.WriteLine("十进制166的八进制表示: "+Convert.ToString(166, 8));
//十进制转十六进制
Console.WriteLine("十进制166的十六进制表示: "+Convert.ToString(166, 16));2.对于通信串口中经常要用到十六进制的格式转换
/// 十进制转为8位的二进制
///
/// 源十进制数据
///
public static string Get10Turn8Bits(int source)
{
string _2BitStringSource = Convert.ToString(source, 2);
string _2BitStringRes = "";
for (int i = 0; i {
_2BitStringRes += "0";
}
_2BitStringRes = _2BitStringRes + _2BitStringSource;
return _2BitStringRes;
}
/// String 转 Hex
///
/// 原始的string数据:FF FF 00 00 08
///
public static byte[] GetHexValue(string str)
{
string[] sourceStr = str.Split(‘ ‘);
byte[] covertHexByte = new byte[sourceStr.Length];
try
{
for (int i = 0; i {
covertHexByte[i] = (byte)(int.Parse(sourceStr[i], System.Globalization.NumberStyles.HexNumber)); ;
}
}
catch
}
/// 将4位的十六进制转化为5位十进制数
///
///
static public string Convert5bitDec(string inputStr)
{
string outputStr = "";
try
{
for (int i = 0; i {
outputStr += Convert.ToInt32(inputStr.Substring(i, 4), 16).ToString("00000");
}
}
catch (Exception){ }
}
/// 字符串转16进制字节数组
///
///
///
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// 将两位ASCII码(一个字节的十六机制)转为十进制数
///
///
///
public static string _2bitAsciiConvertDec(string inputStr)
{
string outputStr = "";
try
{
for (int i = 0; i {
outputStr += (char)Convert.ToInt32(inputStr.Substring(i,2),16);
}
}
catch (Exception) { }
}
文章标题:C#串口通讯中常用的16进制的字节转换
文章链接:http://soscw.com/index.php/essay/75978.html