Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleConvert values between decimal, hexadecimal, octal, and binary in VB .NET
DescriptionThis example shows how to convert values between decimal, hexadecimal, octal, and binary in VB .NET.
Keywordsconvert, decimal, hexadecimal, octal, binary, base, VB.NET
CategoriesVB.NET, Algorithms
 
When you change a text value in any of the text boxes, the Value_TextChanged event handler takes action. That routine calls subroutine DisplayValue, passing it the text box that was modified.

Subroutine DisplayValue checks the text box's name to see how it should interpret the value. If the value is decimal, it uses Long.Parse to get the value. If the value is hexadecimal, it uses Long.Parse with the HexNumber parameter.

If the value is octal, the code ensures that the text begins with &O and then uses CLng. (I don't know of a .NET method for parsing octal. (Let me know if you know of one.)

If the value is binary, the program calls subroutine BinaryToLong.

Having converted the text value into a Long, the program displays it in different bases. It uses ToString to display the decimal value, ToString with the parameter X to display the hexadecimal value, the Oct$ function to display the octal value (let me know if you know of a VB .NET method for formatting as octal), and function LongToBinary to display the binary.

 
Private Sub Value_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    txtDecimal.TextChanged, txtHexadecimal.TextChanged, _
    txtOctal.TextChanged, txtBinary.TextChanged
    DisplayValue(sender)
End Sub

' Display the value in the indicated control in
' the other controls.
Private Sub DisplayValue(ByVal source As TextBox)
    ' Don't recurse.
    Static ignore_events As Boolean = False
    If ignore_events Then Exit Sub
    ignore_events = True

    ' Get the value.
    Dim txt As String
    Dim value As Long
    Try
        Select Case source.Name
            Case "txtDecimal"
                value = Long.Parse(source.Text)
            Case "txtHexadecimal"
                txt = UCase(Trim(source.Text))
                If txt.StartsWith("&H") Then txt = _
                    txt.Substring(2)
                value = Long.Parse(txt, _
                    Globalization.NumberStyles.HexNumber)
            Case "txtOctal"
                txt = UCase(Trim(source.Text))
                If Not txt.StartsWith("&O") Then txt = "&O" _
                    & txt
                value = CLng(txt)
            Case "txtBinary"
                value = BinaryToLong(source.Text)
        End Select
    Catch ex As Exception
        MessageBox.Show("Error parsing input" & vbCrLf & _
            ex.Message, _
            "Input Error", MessageBoxButtons.OK, _
                MessageBoxIcon.Exclamation)
    End Try

    ' Display the value in different formats.
    If source.Name <> "txtDecimal" Then
        txtDecimal.Text = value.ToString()
    End If
    If source.Name <> "txtHexadecimal" Then
        txtHexadecimal.Text = value.ToString("X")
    End If
    If source.Name <> "txtOctal" Then
        txtOctal.Text = "&O" & Oct$(value)
    End If
    If source.Name <> "txtBinary" Then
        txtBinary.Text = LongToBinary(value)
    End If

    ignore_events = False
End Sub
 
Function BinaryToLong examines the binary input text in nibbles (a nibble is half a byte). It loops over each bit in the nibble and adds a corresponding power of 2 to the result if the bit is a 1. It adds the nibble's value in hex to a result string. After it has processed each nibble, the program uses Long.Parse with the HexNumber parameter to convert the hexadecimal string into a Long value.
 
' Convert this binary value into a Long.
Private Function BinaryToLong(ByVal binary_value As String) _
    As Long
    ' Remove any leading &B if present.
    ' (Note: &B is not a standard prefix, it just
    ' makes some sense.)
    binary_value = binary_value.Trim().ToUpper()
    If binary_value.StartsWith("&B") Then binary_value = _
        binary_value.Substring(2)

    ' Strip out spaces in case the bytes are separated
    ' by spaces.
    binary_value = binary_value.Replace(" ", "")

    ' Left pad with zeros so we have a full 64 bits.
    binary_value = New String("0", 64 - _
        binary_value.Length) & binary_value

    ' Read the bits in nibbles from left to right.
    ' (A nibble is half a byte. No kidding!)
    Dim hex_result As String = ""
    For nibble_num As Integer = 0 To 15
        ' Convert this nibble into a hexadecimal string.
        Dim factor As Integer = 1
        Dim nibble_value As Integer = 0

        ' Read the nibble's bits from right to left.
        For bit As Integer = 3 To 0 Step -1
            If binary_value.Substring(nibble_num * 4 + bit, _
                1).Equals("1") Then
                nibble_value += factor
            End If
            factor *= 2
        Next bit

        ' Add the nibble's value to the right of the
        ' result hex string.
        hex_result &= nibble_value.ToString("X")
    Next nibble_num

    ' Convert the result string into a long.
    Return Long.Parse(hex_result, _
        Globalization.NumberStyles.HexNumber)
End Function
 
Function LongToBinary returns a binary text representation of a value. It also considers the value nibble-by-nibble. For each nibble, the code compares the nibble's value to a power of 2 and outputs a 0 or 1 depending on whether the nibble has the same bit set as the power of two.
 
' Convert this Long value into a binary string.
Private Function LongToBinary(ByVal long_value As Long, _
    Optional ByVal separate_bytes As Boolean = True) As _
    String
    ' Convert into hex.
    Dim hex_string As String = long_value.ToString("X")

    ' Zero-pad to a full 16 characters.
    hex_string = New String("0", 16 - hex_string.Length) & _
        hex_string

    ' Read the hexadecimal digits
    ' one at a time from right to left.
    Dim result_string As String = ""
    For digit_num As Integer = 0 To 15
        ' Convert this hexadecimal digit into a
        ' binary nibble.
        Dim digit_value As Integer = _
            Integer.Parse(hex_string.Substring(digit_num, _
            1), Globalization.NumberStyles.HexNumber)

        ' Convert the value into bits.
        Dim factor As Integer = 8
        Dim nibble_string As String = ""
        For bit As Integer = 0 To 3
            If digit_value And factor Then
                nibble_string &= "1"
            Else
                nibble_string &= "0"
            End If
            factor \= 2
        Next bit

        ' Add the nibble's string to the left of the
        ' result string.
        result_string &= nibble_string
    Next digit_num

    ' Add spaces between bytes if desired.
    If separate_bytes Then
        Dim tmp As String = ""
        For i As Integer = 0 To result_string.Length - 8 _
            Step 8
            tmp &= result_string.Substring(i, 8) & " "
        Next i
        result_string = tmp.Substring(0, tmp.Length - 1)
    End If

    ' Return the result.
    Return "&B" & result_string
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated