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進位制字串
/// 位元組陣列轉16進位制字串
/// <param name="bytes"></param>
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進位制
/// 從漢字轉換到16進位制
/// <param name="s"></param>
/// <param name="charset">編碼,如"utf-8","gb2312"</param>
/// <param name="fenge">是否每字元用逗號分隔</param>
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 = "";
str += string.Format("{0:X}", bytes[i]);
if (fenge && (i != bytes.Length - 1))
str += string.
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.