In .NET 5.0 and later you can use the Convert.ToHexString() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//从Base64转bytes
byte[] bytes = Convert.FromBase64String(base64);

//从string转bytes
byte[] bytes = Encoding.UTF8.GetBytes(text);

//从bytes转string
string hex = Convert.ToHexString(bytes);

//从hex转bytes
byte[] bytes = Convert.FromHexString(hex);

//从base64转string
string text = Encoding.UTF8.GetString(Convert.FromBase64String(base64));

//从bytes到base64
string base64 = Convert.ToBase64String(bytes);

//从string到base64
string base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(text));

参考1

1
2
3
4
5
6
7
8
9
10
using System;
using System.Text;

string value = "Hello world";

byte[] bytes = Encoding.UTF8.GetBytes(value);
string hexString = Convert.ToHexString(bytes);

Console.WriteLine($"String value: "{value}"");
Console.WriteLine($"Hex value: "{hexString}"");

Output

1
2
String value: "Hello world"
Hex value: "48656C6C6F20776F726C64"

参考2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class HexadecimalEncoding
{
public static string ToHexString(string str)
{
var sb = new StringBuilder();

var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes)
{
sb.Append(t.ToString("X2"));
}

return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
}

public static string FromHexString(string hexString)
{
var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++)
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}

return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
}
}

参考
https://zetcode.com/csharp/bytearray-hexstring/
https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types