Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex number (not ASCII hex value) to string in VB.NET

Tags:

string

vb.net

hex

I've tried searching for this, but most people just want to convert hex values into their ASCII equivalents. That's not what I am looking to do.

I'm looking to see if VB.NET has a simple built-in function to do this:

    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

Is there a more elegant way to accomplish the same thing as that code?

like image 395
avword Avatar asked Sep 19 '10 22:09

avword


2 Answers

Use ToString with the X format specifier:

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

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

And if you did just want to do a nibble at a time for some reason then you could just mask/shift out the various bits of the number beforehand:

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)
like image 151
LukeH Avatar answered Sep 21 '22 11:09

LukeH


As a function

<FlagsAttribute()> _
Public Enum whichNibble As Integer
    'byte
    '7654 3210
    ' msn  lsn
    lsn = 1
    msn = 2
    both = lsn Or msn
End Enum

Private Function GetNibble(ByVal aByte As Byte, _
                          Optional ByVal whNib As whichNibble = whichNibble.lsn) As String
    Select Case whNib
        Case whichNibble.both
            Return aByte.ToString("X2")
        Case whichNibble.lsn
            Return (aByte And &HF).ToString("X")
        Case whichNibble.msn
            Return ((aByte >> 4) And &HF).ToString("X")
    End Select
End Function
like image 29
dbasnett Avatar answered Sep 22 '22 11:09

dbasnett