在c#中将字符转换为CP1252 Hex(Convert character to CP1252 Hex in c#)

编程入门 行业动态 更新时间:2024-10-14 12:28:33
在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

更多推荐

本文发布于:2023-08-07 01:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   字符   Convert   Hex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!