C#写一个字符16进制转10进制的方法,写一个字符16进制转utf-8的方法
时间: 2023-11-22 14:54:36 浏览: 94
字符16进制转10进制的方法:
```csharp
public static int HexToDecimal(char hexChar)
{
int result = 0;
if (hexChar >= '0' && hexChar <= '9')
{
result = hexChar - '0';
}
else if (hexChar >= 'a' && hexChar <= 'f')
{
result = hexChar - 'a' + 10;
}
else if (hexChar >= 'A' && hexChar <= 'F')
{
result = hexChar - 'A' + 10;
}
return result;
}
```
字符16进制转utf-8的方法:
```csharp
public static string HexToUtf8(string hexString)
{
byte[] bytes = new byte[hexString.Length / 2];
for (int i = 0; i < hexString.Length; i += 2)
{
bytes[i / 2] = (byte)((HexToDecimal(hexString[i]) << 4) | HexToDecimal(hexString[i + 1]));
}
return Encoding.UTF8.GetString(bytes);
}
```
这里需要用到之前写的字符16进制转10进制的方法。将每两个字符转为一个byte,然后使用UTF-8编码将byte数组转为字符串。
阅读全文