c# - 将带有特殊字符的字符串转换为十六进制 - C#
问题描述
解决方案
这是由于字节顺序以及不同的整数和字符串编码。
char cc = '…';
Console.WriteLine(cc);
// 2026 <-- note, hex value differs from byte representation shown below
Console.WriteLine(((int)cc).ToString("x"));
// 26200000
Console.WriteLine(BytesToHex(BitConverter.GetBytes((int)cc)));
// 2620
Console.WriteLine(BytesToHex(Encoding.GetEncoding("utf-16").GetBytes(new[] { cc })));
您不应将字符视为整数。编码字符串有很多不同的方法,.net 内部使用 UTF-16。并且所有编码都适用于字节,而不是整数。将字符显式转换为整数可能会导致意外结果,例如您的结果。为什么不获取所需的编码并通过字节处理Encoding.GetBytes
?
void Main()
{
// output you expect 0xB4006F00B8007300E700500051005D002800C2004600120026206100
Console.WriteLine(BytesToHex(Encoding.GetEncoding("utf-16").GetBytes("´o¸sçPQ](ÂF\u0012…a")));
}
public static string BytesToHex(byte[] bytes)
{
// whatever way to convert bytes to hex
return "0x" + BitConverter.ToString(bytes).Replace("-", "");
}
推荐阅读
- python - Python,在给定的摩尔斯电码中找到所有可能的字母组合
- java - OpenJDK 64 位服务器 VM 警告:选项 -Xverify:none 和 -noverify 在 JDK 13 中已弃用,可能会在未来版本中删除
- python - 加载预训练模型时出现 Keras 导入错误
- java - 无法使用 JDBC 读取特殊字符
- java - 有没有办法静态访问注释中的默认值?
- c++ - C++ 中奇怪的函数声明和 lambdas
- javascript - 'autoposition' 属性未在 JsPanel 之间应用
- javascript - 如何在第一个选项卡之后从网页选项卡获取单击事件的单元格值?
- c# - 如何为 .txt 文件中的每个添加行分配一个 ID 值(ASP.NET MVC / C#)
- jsp - 带有 JDBC 的 JSF 项目,我无法在 Servlet 上调用 DAO