C#串口通訊中常用的16進制的字節轉換
1.對於通訊協議的十六進制數值進行簡單轉換
//二進制轉十進制
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.對於通信串口中經常要用到十六進制的格式轉換
/// <summary>
/// 十進制轉為8位的二進制
/// </summary>
/// <param name="source">源十進制數據</param>
/// <returns>八位的二進制數</returns>
public static string Get10Turn8Bits(int source)
{
string _2BitStringSource = Convert.ToString(source, 2);
string _2BitStringRes = "";
for (int i = 0; i < 8 - _2BitStringSource.Length; i++)
{
//不滿8位就補零
_2BitStringRes += "0";
}
_2BitStringRes = _2BitStringRes + _2BitStringSource;
return _2BitStringRes;
}
// <summary>
/// String 轉 Hex
/// </summary>
/// <param name="str">原始的string數據:FF FF 00 00 08</param>
/// <returns>返回hex字節數組</returns>
public static byte[] GetHexValue(string str)
{
string[] sourceStr = str.Split(‘ ‘);
byte[] covertHexByte = new byte[sourceStr.Length];
try
{
for (int i = 0; i < sourceStr.Length; i++)
{
covertHexByte[i] = (byte)(int.Parse(sourceStr[i], System.Globalization.NumberStyles.HexNumber)); ;
}
}
catch
{ }
return covertHexByte;
}
/// <summary>
/// 將4位的十六進制轉化為5位十進制數
/// </summary>
/// <returns>五位十進制數</returns>
static public string Convert5bitDec(string inputStr)
{
string outputStr = "";
try
{
for (int i = 0; i < inputStr.Length; i = i + 4)
{
outputStr += Convert.ToInt32(inputStr.Substring(i, 4), 16).ToString("00000");
}
}
catch (Exception){ }
return outputStr;
}
/// <summary>
/// 字符串轉16進制字節數組
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
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.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 將兩位ASCII碼(一個字節的十六機制)轉為十進制數
/// </summary>
/// <param name="inputStr"></param>
/// <returns></returns>
public static string _2bitAsciiConvertDec(string inputStr)
{
string outputStr = "";
try
{
for (int i = 0; i < inputStr.Length; i = i + 2)
{
outputStr += (char)Convert.ToInt32(inputStr.Substring(i,2),16);
}
}
catch (Exception) { }
return outputStr;
}
C#串口通訊中常用的16進制的字節轉換