首页 > 解决方案 > 将带有特殊字符的字符串转换为十六进制 - C#

问题描述

标签: c#stringcharacter-encodinghexspecial-characters

解决方案


这是由于字节顺序以及不同的整数和字符串编码。

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("-", "");
}

推荐阅读