tags:

views:

107

answers:

2

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 todo.

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

Anyone know of a more elegant way to accomplish the same thing as that code?

+2  A: 

Can't you just 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)
LukeH
THANK YOU! That is exactly what I was looking for. Works great.
avword
A: 

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
dbasnett