标签:
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));
/// <summary>
/// 十进制转为8位的二进制
/// </summary>
/// <param>源十进制数据</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>原始的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></param>
/// <returns></returns>
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.WordStr(" ", "");
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></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;
}
标签:
原文地点:https://www.cnblogs.com/Qxian/p/8698768.html
,