c# 读hex_C# Hex编码和解码
/// 從字符串轉(zhuǎn)換到16進(jìn)制表示的字符串
/// 編碼,如"utf-8","gb2312"
/// 是否每字符用逗號(hào)分隔
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進(jìn)制轉(zhuǎn)換成utf編碼的字符串
/// 編碼,如"utf-8","gb2312"
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";//空格
throw new ArgumentException("hex is not a valid number!", "hex");
}
// 需要將 hex 轉(zhuǎn)換成 byte 數(shù)組。
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每?jī)蓚€(gè)字符是一個(gè) 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);
}
總結(jié)
以上是生活随笔為你收集整理的c# 读hex_C# Hex编码和解码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言入门1.2.3 百度云,C语言入门
- 下一篇: C++打开文件的方式