Last active
November 9, 2020 12:37
-
-
Save fpGHwd/0b9123c01440fc953941 to your computer and use it in GitHub Desktop.
c# string to hex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment