Private Function BinaryToHex(ByRef BitString As String) As String
' If the string is empty return an empty string
If BitString.Length = 0 Then Return ""
' If the bitString contains characters that ain't One or Zero, return Empty String
If System.Text.RegularExpressions.Regex.IsMatch(BitString, "[01]+") = False Then Return ""
' Initially make the string empty
BinaryToHex = ""
' define a nibble (4-bits / half a byte)
Dim nibble As String = ""
' Start at the righthandside.
Dim i As Integer = BitString.Length
' while not reached the lefthandside
While i > 0
i -= 1
' Add the bit a position i to the start of the nibble
nibble = BitString(i) & nibble
' if reach the end of bitstring & the nibble length is less than four.
If i = 0 And nibble.Length < 4 Then
' Prepend the nibble with the required number of Zeros to make the nibble have length of four.
nibble = StrDup(4 - nibble.Length, "0") & nibble
End If
' Find the case which matches the nibble and add the corrisponding hexadecimal representation to
' the begining of BinaryToHex String.
Select Case nibble
Case "0000" : BinaryToHex = "0" & BinaryToHex
Case "0001" : BinaryToHex = "1" & BinaryToHex
Case "0010" : BinaryToHex = "2" & BinaryToHex
Case "0011" : BinaryToHex = "3" & BinaryToHex
Case "0100" : BinaryToHex = "4" & BinaryToHex
Case "0101" : BinaryToHex = "5" & BinaryToHex
Case "0110" : BinaryToHex = "6" & BinaryToHex
Case "0111" : BinaryToHex = "7" & BinaryToHex
Case "1000" : BinaryToHex = "8" & BinaryToHex
Case "1001" : BinaryToHex = "9" & BinaryToHex
Case "1010" : BinaryToHex = "A" & BinaryToHex
Case "1011" : BinaryToHex = "B" & BinaryToHex
Case "1100" : BinaryToHex = "C" & BinaryToHex
Case "1101" : BinaryToHex = "D" & BinaryToHex
Case "1110" : BinaryToHex = "E" & BinaryToHex
Case "1111" : BinaryToHex = "F" & BinaryToHex
End Select
nibble = ""
End While
' Return the BinaryToHex String
Return BinaryToHex ' Not required.
End Function