C#字符常用转码
这个参考地址总结的比较全:https://blog.csdn.net/u011089530/article/details/103776198
没有亲测,做个笔记参考哦!!
1.GBK 十六进制转字符(包含汉字)
string code = "D6 B1 B2 E5 CA BD 32 30 31 39 31 32 32 37 30 30 30 32 31 0D";
string[] codeArr = code.Split(' ');
int codeLen = codeArr.Length;
byte[] codeByteArr = new byte[codeArr.Length];
if (codeLen > 0)
{
for (int i = 0; i < codeLen; i++)
{
codeByteArr[i] = (byte)Convert.ToByte(codeArr[i], 16);
}
}
string res = Encoding.GetEncoding("GBK").GetString(codeByteArr);//结果:直插式2019122700021\r
2.字符(汉字)转 十六进制GBK
string chinese = "汉字哦110";
byte[] gbk = Encoding.GetEncoding("GBK").GetBytes(chinese);
string gbkStr = ""; string byteStr = "";
foreach (byte b in gbk)
{
//s1 += Convert.ToString(b, 16)+" ";
gbkStr += string.Format("{0:X2}", b) + " ";
byteStr += b + " ";
}
//结果:
gbkStr :BA BA D7 D6 C5 B6 31 31 30
byteStr :186 186 215 214 197 182 49 49 48
3.Unicode十六进制转字符(包含汉字)
string code = "D6 B1 B2 E5 CA BD 32 30 31 39 31 32 32 37 30 30 30 32 31 0D";
string[] codeArr = code.Split(' ');
int codeLen = codeArr.Length;
byte[] codeByteArr = new byte[codeArr.Length];
if (codeLen > 0)
{
for (int i = 0; i < codeLen; i++)
{
codeByteArr[i] = (byte)Convert.ToByte(codeArr[i], 16);
}
}
string res = Encoding.GetEncoding("Unicode").GetString(codeByteArr);
//结果:直插式2019122700021\r
4.字符(汉字)转 十六进制UniCode
string chinese = "汉字哦110";
byte[] uniCode = Encoding.Unicode.GetBytes(chinese);
string uniStr = ""; string uniByte = "";
foreach (byte b in uniCode)
{
//s2 += Convert.ToString(b, 16) + " ";
uniStr += string.Format("{0:X2}", b) + " ";
uniByte += b + " ";
}
//结果:
49 6C 57 5B E6 54 31 00 31 00 30 00
73 108 87 91 230 84 49 0 49 0 48 0
5.UTF-8十六进制转字符(包含汉字)
string code = "D6 B1 B2 E5 CA BD 32 30 31 39 31 32 32 37 30 30 30 32 31 0D";
string[] codeArr = code.Split(' ');
int codeLen = codeArr.Length;
byte[] codeByteArr = new byte[codeArr.Length];
if (codeLen > 0)
{
for (int i = 0; i < codeLen; i++)
{
codeByteArr[i] = (byte)Convert.ToByte(codeArr[i], 16);
}
}
string res = Encoding.GetEncoding("UTF-8").GetString(codeByteArr);
//结果:直插式2019122700021\r
6.字符(汉字)转 十六进制UTF-8
string chinese = "汉字哦110";
byte[] uniCode = Encoding.UTF8.GetBytes(chinese);
string uniStr = ""; string uniByte = "";
foreach (byte b in uniCode)
{
//s2 += Convert.ToString(b, 16) + " ";
uniStr += string.Format("{0:X2}", b) + " ";
uniByte += b + " ";
}
//结果:
49 6C 57 5B E6 54 31 00 31 00 30 00
73 108 87 91 230 84 49 0 49 0 48 0
“fool me once,shame on you. fool me twice, shame on me.”,翻译过来的意思是“愚弄我一次,是你坏;愚弄我两次,是我蠢”。