如何将字节数组转换为十六进制字符串,反之亦然?
当前回答
我怀疑这样的速度会使大多数其他测试失败。。。
Public Function BufToHex(ByVal buf() As Byte) As String
Dim sB As New System.Text.StringBuilder
For i As Integer = 0 To buf.Length - 1
sB.Append(buf(i).ToString("x2"))
Next i
Return sB.ToString
End Function
其他回答
对于Java 8,我们可以使用Byte.toUnsignedInt
public static String convertBytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte byt : bytes) {
int decimal = Byte.toUnsignedInt(byt);
String hex = Integer.toHexString(decimal);
result.append(hex);
}
return result.toString();
}
.NET 5已添加Convert.ToHexString方法。
对于使用旧版本.NET的用户
internal static class ByteArrayExtensions
{
public static string ToHexString(this byte[] bytes, Casing casing = Casing.Upper)
{
Span<char> result = stackalloc char[0];
if (bytes.Length > 16)
{
var array = new char[bytes.Length * 2];
result = array.AsSpan();
}
else
{
result = stackalloc char[bytes.Length * 2];
}
int pos = 0;
foreach (byte b in bytes)
{
ToCharsBuffer(b, result, pos, casing);
pos += 2;
}
return result.ToString();
}
private static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
{
uint difference = (((uint)value & 0xF0U) << 4) + ((uint)value & 0x0FU) - 0x8989U;
uint packedResult = ((((uint)(-(int)difference) & 0x7070U) >> 4) + difference + 0xB9B9U) | (uint)casing;
buffer[startingIndex + 1] = (char)(packedResult & 0xFF);
buffer[startingIndex] = (char)(packedResult >> 8);
}
}
public enum Casing : uint
{
// Output [ '0' .. '9' ] and [ 'A' .. 'F' ].
Upper = 0,
// Output [ '0' .. '9' ] and [ 'a' .. 'f' ].
Lower = 0x2020U,
}
改编自.NET存储库https://github.com/dotnet/runtime/blob/v5.0.3/src/libraries/System.Private.CoreLib/src/System/Convert.cshttps://github.com/dotnet/runtime/blob/v5.0.3/src/libraries/Common/src/System/HexConverter.cs
我怀疑这样的速度会使大多数其他测试失败。。。
Public Function BufToHex(ByVal buf() As Byte) As String
Dim sB As New System.Text.StringBuilder
For i As Integer = 0 To buf.Length - 1
sB.Append(buf(i).ToString("x2"))
Next i
Return sB.ToString
End Function
您可以使用BitConverter.ToString方法:
byte[] bytes = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256}
Console.WriteLine( BitConverter.ToString(bytes));
输出:
00-01-02-04-08-10-20-40-80-FF
更多信息:BitConverter.ToString方法(Byte[])
我猜它的速度值16个额外的字节。
static char[] hexes = new char[]{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static string ToHexadecimal (this byte[] Bytes)
{
char[] Result = new char[Bytes.Length << 1];
int Offset = 0;
for (int i = 0; i != Bytes.Length; i++) {
Result[Offset++] = hexes[Bytes[i] >> 4];
Result[Offset++] = hexes[Bytes[i] & 0x0F];
}
return new string(Result);
}