在c#中将字符转换为CP1252 Hex(Convert character to CP1252 Hex in c#)
我写了一个函数将字符串转换为十六进制字符串。 所以“abc”将转换为“616263”。
这是功能:
private string StringToHex(string myString) { int ctr, li_max; string ls_hex = ""; li_max = myString.Length; for(ctr = 0; ctr < li_max; ctr++) ls_hex = ls_hex + (Convert.ToInt16(myString[ctr])).ToString("x2"); return ls_hex; }但是,当我有像“<abc”这样的unicode字符时,我得到“2039616263”。 所以我的第一个角色转换为2039(unicode)。 我想得到“8B616263”(CP1252)。 见下图:
如何获取正确编码的十六进制值? 即:8B而不是2039
I wrote a function to convert a string to a hex string. So "abc" would be converted to "616263".
Here is the function:
private string StringToHex(string myString) { int ctr, li_max; string ls_hex = ""; li_max = myString.Length; for(ctr = 0; ctr < li_max; ctr++) ls_hex = ls_hex + (Convert.ToInt16(myString[ctr])).ToString("x2"); return ls_hex; }However, when I have unicode characters like "‹abc" I get "2039616263". So my first character is converted to 2039 (unicode). I wanted to get "8B616263" (CP1252). See image below:
How can I get the hex value for the correct encoding? ie: 8B instead of 2039
最满意答案
您需要使用CP1252编码来获取字符串的字节:
private string StringToHex(string myString) { byte[] bytes = Encoding.GetEncoding(1252).GetBytes(myString); return string.Concat(bytes.Select(b => b.ToString("X2"))); }我的输出是
8B616263
You need to get use the CP1252 encoding to get the bytes of the string:
private string StringToHex(string myString) { byte[] bytes = Encoding.GetEncoding(1252).GetBytes(myString); return string.Concat(bytes.Select(b => b.ToString("X2"))); }My output is
8B616263
更多推荐
发布评论