示例
[Visual Basic, C#] 下面的示例说明将字节数组转换为十六进制值字符串时 Byte 的用法。
[Visual Basic]
Class HexTest
Private Shared hexDigits As Char() = {"0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c}
Public Shared Function ToHexString(bytes() As Byte) As String
Dim hexStr As String = ""
Dim i As Integer
For i = 0 To bytes.Length - 1
hexStr = hexStr + Hex(bytes(i))
Next i
Return hexStr
End Function 'ToHexString
Shared Sub Main()
Dim b As Byte() = {&H0, &H12, &H34, &H56, &HAA, &H55, &HFF}
Console.WriteLine(ToHexString(b))
End Sub 'Main
End Class 'HexTest
[C#]
class HexTest
{
static char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static string ToHexString(byte[] bytes) {
char[] chars = new char[bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++) {
int b = bytes[i];
chars[i * 2] = hexDigits[b >> 4];
chars[i * 2 + 1] = hexDigits[b & 0xF];
}
return new string(chars);
}
static void Main() {
byte[] b = {0x00, 0x12, 0x34, 0x56, 0xAA, 0x55, 0xFF};
Console.WriteLine(ToHexString(b));
}
}