c#进制转换:c#实现16进制与字符串、字节数组相互转换

发布时间:2020-02-25编辑:脚本学堂
c#进制转换代码大全,c#编程中实现进程转换的多种方法,包括c#进制转换函数的用法,C#进制转换代码实现二进制、十六进制、十进制互转,以及C#实现十进制和十六进制转换的方法。

一、c#实现16进制与字符串、字节数组相互转换

在串口通讯过程中,经常要用到 16进制与字符串、字节数组之间的转换

复制代码 代码示例:
/// <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;
}
字节数组转16进制字符串
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
从汉字转换到16进制
/// <summary>
/// 从汉字转换到16进制
/// </summary>
/// <param name="s"></param>
/// <param name="charset">编码,如"utf-8","gb2312"</param>
/// <param name="fenge">是否每字符用逗号分隔</param>
/// <returns></returns>
public static string ToHex(string s, string charset, bool fenge)
{
if ((s.Length % 2) != 0)
{
s += " ";//空格
//throw new ArgumentException("s is not valid chinese string!");
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
byte[] bytes = chs.GetBytes(s);
string str = "";
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X}", bytes[i]);
if (fenge && (i != bytes.Length - 1))
{
str += string.Format("{0}", ",");
}
}
return str.ToLower();
}
16进制转换成汉字
///<summary>
/// 从16进制转换成汉字
/// </summary>
/// <param name="hex"></param>
/// <param name="charset">编码,如"utf-8","gb2312"</param>
/// <returns></returns>
public static string UnHex(string hex, string charset)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("n", "");
hex = hex.Replace("", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 hex 转换成 byte 数组。
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每两个字符是一个 byte。
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
// Rethrow an exception with custom message.
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
return chs.GetString(bytes);
}

二、C# 进制转换(二进制、十六进制、十进制互转)

由于二进制数在C#中无法直接表示,所以所有二进制数都用一个字符串来表示 。

例如:
 

复制代码 代码示例:
//二进制: 1010 表示为 字符串:"1010"
int d = 10; 
 
//十进制转二进制字符串 
 Console.WriteLine(Convert.ToString(d,2)); 
//输出: 1010 
 
//十进制转十六进制字符串 
Console.WriteLine(Convert.ToString(d,16)); 
//输出: a 
 
//二进制字符串转十进制数 
string bin = "1010"; 
Console.WriteLine(Convert.ToInt32(bin,2)); 
//输出: 10 
 
//二进制字符串转十六进制数 
string bin = "1010"; 
Console.WriteLine(string.Format("{0:x}",Convert.ToInt32(bin,2)); 
//输出: a 
 
//十六进制转二进制字符串 
Console.WriteLine(Convert.ToString(0xa,2)); 
//输出: 1010 
 
//十六进制转十进制数 
Console.WriteLine(Convert.ToString(0xa,10)); 
//输出: 10

三、c#实现进制间转换的综合例子

代码:
 

复制代码 代码示例:

/// <summary>
///
/// </summary>
/// <param name="bytes"></param>
/// <param name="iLength"></param>
/// <returns></returns>
public static string ToHexString(byte[] bytes, int iLength) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();

if (bytes.Length < iLength)
{
iLength = bytes.Length;
}

for (int i = 0; i < iLength; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}

/// <summary>
/// 将byte数组转换为16进制字符串
/// </summary>
/// <param name="bytes">要转换的数组</param>
/// <param name="iStart">数组下标</param>
/// <param name="iLength">长度</param>
/// <returns></returns>
public static string ToHexString(byte[] bytes, int iStart, int iLength) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();

//缓冲区长度问题,需清空缓冲区
if (bytes.Length < (iLength + iStart))
{
iLength = bytes.Length;
}

for (int i = iStart; i < iLength + iStart; i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}

/// <summary>
///
/// </summary>
/// <param name="hexString"></param>
/// <param name="discarded"></param>
/// <returns></returns>
public static byte[] GetBytes(string hexString, out int discarded)
{
discarded = 0;
string newString = "";
char c;
// remove all none A-F, 0-9, characters
for (int i = 0; i < hexString.Length; i++)
{
c = hexString[i];
if (Uri.IsHexDigit(c))
newString += c;
else
discarded++;
}
// if odd number of characters, discard last character
if (newString.Length%2 != 0)
{
discarded++;
newString = newString.Substring(0, newString.Length - 1);
}

return HexToByte(newString);
}

/// <summary>
/// Converts from binary coded decimal to integer
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static uint BcdToDec(uint num)
{
return HornerScheme(num, 0x10, 10);
}

/// <summary>
/// Converts from integer to binary coded decimal
/// </summary>
/// <param name="num"></param>
/// <returns></returns>
public static uint DecToBcd(uint num)
{
return HornerScheme(num, 10, 0x10);
}

private static uint HornerScheme(uint num, uint divider, uint factor)
{
uint remainder = 0, quotient = 0, result = 0;
remainder = num%divider;
quotient = num/divider;
if (!(quotient == 0 && remainder == 0))
result += HornerScheme(quotient, divider, factor)*factor + remainder;
return result;
}

/// <summary>
/// byte数组尾部0截取函数
/// </summary>
/// <param name="buf">原始byte数组</param>
/// <param name="iLength">要截取的长度</param>
/// <returns>截取后的数组</returns>
public static byte[] InterceptByte(byte[] buf, int iLength)
{
StringBuilder sb = new StringBuilder(iLength*2);
sb = sb.Append(ToHexString(buf, (short) iLength));
int discarded = 0;
byte[] bReturn = GetBytes(sb.ToString(), out discarded);

if (discarded > 0)
{
throw new Exception("byte数组截取有数据丢失!");
}
return bReturn;
}

/// <summary>
///
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexToByte(string hexString)
{
if (string.IsNullOrEmpty(hexString))
{
hexString = "00";
}
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>
/// 日期转BCD数组
/// </summary>
/// <param name="dateTime"></param>
/// <param name="type">4 6 7</param>
/// <returns></returns>
public static byte[] DateTimeToBCD(DateTime dateTime, ushort type)
{
string strServerTime = string.Format("{0:yyyyMMddHHmmss}", dateTime);

byte[] bcd = new byte[type];
if (type == 4)
{
bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(0, 2))).ToString("D2"));
bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2"));
bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2"));
bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2"));
}
if (type == 6)
{
bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2"));
bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2"));
bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2"));
bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(8, 2))).ToString("D2"));
bcd[4] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(10, 2))).ToString("D2"));
bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(12, 2))).ToString("D2"));
}
if (type == 7)
{
bcd[0] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(0, 2))).ToString("D2"));
bcd[1] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(2, 2))).ToString("D2"));
bcd[2] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(4, 2))).ToString("D2"));
bcd[3] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(6, 2))).ToString("D2"));
bcd[4] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(8, 2))).ToString("D2"));
bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(10, 2))).ToString("D2"));
bcd[5] = byte.Parse(DecToBcd(uint.Parse(strServerTime.Substring(12, 2))).ToString("D2"));
}
return bcd;
}

/// <summary>
/// BCD时间转日期时间
/// </summary>
/// <param name="bcdTime"></param>
/// <param name="type"></param>
/// <returns></returns>
public static DateTime BCDToDateTime(byte[] bcdTime, ushort type)
{
StringBuilder sb = new StringBuilder();
if (type == 4) //4位BCD码的日期
{
sb.Append(BcdToDec(bcdTime[0]).ToString("D2"));
sb.Append(BcdToDec(bcdTime[1]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[3]).ToString("D2") + " ");
}
if (type == 6) //6位BCD码的时间
{
sb.Append(DateTime.Now.ToString("yyyy").Substring(0, 2));
sb.Append(BcdToDec(bcdTime[0]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[1]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2") + " ");
sb.Append(BcdToDec(bcdTime[3]).ToString("D2") + ":");
sb.Append(BcdToDec(bcdTime[4]).ToString("D2") + ":");
sb.Append(BcdToDec(bcdTime[5]));
}
if (type == 7) //7位BCD码的日期
{
sb.Append(BcdToDec(bcdTime[0]).ToString("D2"));
sb.Append(BcdToDec(bcdTime[1]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[2]).ToString("D2"));
sb.Append('-' + BcdToDec(bcdTime[3]).ToString("D2") + " ");
sb.Append(BcdToDec(bcdTime[4]).ToString("D2") + ":");
sb.Append(BcdToDec(bcdTime[5]).ToString("D2") + ":");
sb.Append(BcdToDec(bcdTime[6]));
}

DateTime dt;
//2011-3-26 当日期出错时的处理
DateTime.TryParse(sb.ToString(), out dt);

return dt;
}
}
}

四、C# 十进制和十六进制转换
在C#中,十进制和十六进制转换非常简单,方法如下:

十进制转为十六进制:
 

复制代码 代码示例:
int a = 100;
String strA = a.ToString("x8");

十六进制转为十进制:
 

复制代码 代码示例:

int b= Int32.Parse("266", System.Globalization.NumberStyles.HexNumber);
/// <summary>
/// 十六进制换算为十进制
/// </summary>
/// <param name="strColorValue"></param>
/// <returns></returns>
public static int GetHexadecimalValue(String strColorValue)
{
char[] nums = strColorValue.ToCharArray();
int total = 0;
try
{
for (int i = 0; i < nums.Length; i++)
{
String strNum = nums[i].ToString().ToUpper();
switch (strNum)
{
case "A":
strNum = "10";
break;
case "B":
strNum = "11";
break;
case "C":
strNum = "12";
break;
case "D":
strNum = "13";
break;
case "E":
strNum = "14";
break;
case "F":
strNum = "15";
break;
default:
break;
}
double power = Math.Pow(16, Convert.ToDouble(nums.Length - i - 1));
total += Convert.ToInt32(strNum) * Convert.ToInt32(power);
}

}
catch (System.Exception ex)
{
String strErorr = ex.ToString();
return 0;
}
return total;
}