在VB.NET中字符串的十六进制数字(不是ASCII十六进制值)

我试过搜索这个,但大多数人只想将十六进制值转换为它们的ASCII等价物.这不是我想要做的.

我想看看VB.NET是否有一个简单的内置函数来执行此操作:

    Private Function NibbleToString(ByVal Nibble As Byte) As String
    Dim retval As String = String.Empty
    Select Case Nibble

        Case &H0
            retval = "0"
        Case &H1
            retval = "1"
        Case &H2
            retval = "2"
        Case &H3
            retval = "3"
        Case &H4
            retval = "4"
        Case &H5
            retval = "5"
        Case &H6
            retval = "6"
        Case &H7
            retval = "7"
        Case &H8
            retval = "8"
        Case &H9
            retval = "9"
        Case &HA
            retval = "A"
        Case &HB
            retval = "B"
        Case &HC
            retval = "C"
        Case &HD
            retval = "D"
        Case &HE
            retval = "E"
        Case &HF
            retval = "F"
    End Select

    Return retval
End Function

是否有更优雅的方式来完成与该代码相同的事情?

最佳答案
X format specifier一起使用ToString:

Dim b As Byte = &HA3
Console.WriteLine(b.ToString("X"))    ' displays "A3"

Dim i As Integer = &H12AB89EF
Console.WriteLine(i.ToString("X"))    ' displays "12AB89EF"

如果你只是想出于某种原因一次只做一个半字节,那么你可以事先掩盖/移出数字的各个位:

Dim b As Byte = &H5E
Console.WriteLine((b And &HF).ToString("X"))    ' displays "E" (low nibble)
Console.WriteLine((b >> 4).ToString("X"))       ' displays "5" (high nibble)

转载注明原文:在VB.NET中字符串的十六进制数字(不是ASCII十六进制值) - 代码日志