none
VB.net binary number formating RRS feed

  • Question

  • Hello,

    I am working on a number converter calculator and I need to show my binary output (after converting it from decimal) as 0000 0000 0000 0000 0000 0000 0000 0000. I have the calculator working fine just the visual format is not working.

    If anyone could me help with this, I'd really appreciate that.

    Thanks.



    • Edited by imr4z Monday, March 19, 2018 3:32 AM
    Monday, March 19, 2018 3:29 AM

Answers

  • I need to show my binary output (after converting it from decimal) as 0000 0000 0000 0000 0000 0000 0000 0000.

    Example code implementing Acamar's suggestions:

    Function binformat(ByVal num As Int32) As String
        Dim s As New StringBuilder(Convert.ToString(num, 2).PadLeft(32, "0"c))
        For i = 28 To 4 Step -4
            s.Insert(i, " "c)
        Next
        Return s.ToString
    End Function
    

    E&OE

    - Wayne

    • Proposed as answer by dbasnett Monday, March 19, 2018 3:36 PM
    • Marked as answer by imr4z Monday, March 19, 2018 10:31 PM
    Monday, March 19, 2018 7:51 AM

All replies

  • I am working on a number converter calculator and I need to show my binary output (after converting it from decimal) as 0000 0000 0000 0000 0000 0000 0000 0000.

    There are many ways to do this.  Perhaps the simplest is to use bitconverter and convert to base 2 (binary), pad left with zeroes to get a length of 32, then copy groups of 4, inserting the spaces.  See:

    https://msdn.microsoft.com/en-us/library/14kwkz77%28v=vs.110%29.aspx

    • Proposed as answer by WayneAKing Monday, March 19, 2018 7:45 AM
    Monday, March 19, 2018 3:59 AM
  • Hi imr4z,

    If you want to show binary output like this 0000 0000 0000 0000 0000 0000, you can consider the following code:

     Dim value1 = System.Text.RegularExpressions.Regex.Replace(out, "(\w{4})", "$1 ").Trim()


    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, March 19, 2018 6:10 AM
    Moderator
  • I need to show my binary output (after converting it from decimal) as 0000 0000 0000 0000 0000 0000 0000 0000.

    Example code implementing Acamar's suggestions:

    Function binformat(ByVal num As Int32) As String
        Dim s As New StringBuilder(Convert.ToString(num, 2).PadLeft(32, "0"c))
        For i = 28 To 4 Step -4
            s.Insert(i, " "c)
        Next
        Return s.ToString
    End Function
    

    E&OE

    - Wayne

    • Proposed as answer by dbasnett Monday, March 19, 2018 3:36 PM
    • Marked as answer by imr4z Monday, March 19, 2018 10:31 PM
    Monday, March 19, 2018 7:51 AM
  • I need to show my binary output (after converting it from decimal) as 0000 0000 0000 0000 0000 0000 0000 0000.

    Example code implementing Acamar's suggestions:

    Function binformat(ByVal num As Int32) As String
        Dim s As New StringBuilder(Convert.ToString(num, 2).PadLeft(32, "0"c))
        For i = 28 To 4 Step -4
            s.Insert(i, " "c)
        Next
        Return s.ToString
    End Function
    

    E&OE

    - Wayne

    Similar to above but using Generics.  Works with Int16, Int32, Int64.

        Private Function ToBinStringInt(Of T)(num As T) As String
            Dim L As Integer = 0
            Select Case True 'select length
                Case TypeOf num Is Int32
                    L = 32
                Case TypeOf num Is Int16
                    L = 16
                Case TypeOf num Is Int64
                    L = 64
                Case Else
                    Return ""
            End Select
    
            Dim n As Long = CLng(CTypeDynamic(num, GetType(Long)))
            Dim s As New System.Text.StringBuilder(Convert.ToString(n, 2).PadLeft(L, "0"c))
            Dim rv As New System.Text.StringBuilder(s.Length * 2) 'return value
    
            Dim cpy(4) As Char
            cpy(4) = " "c
    
            For idx As Integer = 0 To s.Length - 4 Step 4
                s.CopyTo(idx, cpy, 0, 4)
                rv.Append(cpy)
            Next
            Return rv.ToString.Trim
    
        End Function
    

    Test

            Dim s As String
            Dim i16 As Int16 = 1023
            s = ToBinStringInt(i16)
    
            Dim i32 As Int32 = 1023
            s = ToBinStringInt(i32)
    
            Dim i64 As Int64 = 1023
            s = ToBinStringInt(i64)
    


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it" - MSDN User JohnWein

    Monday, March 19, 2018 4:06 PM
  • Thank you so much <g class="gr_ gr_17 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" data-gr-id="17" id="17">everyone</g>. I tried to use some of the suggestions you had but I am pretty sure it's my fault that I couldn't get them to work. I am still a very beginning level vb.net programmer. Please excuse my ignorance. This is the code I have,

    Private Sub btnConverter_Click(sender As Object, e As EventArgs) Handles btnConverter.Click
    
    If strFocused = "Decimal" And (Not txtDecimal1.Text = "") Then
                Dim numConverter1D As Integer = Integer.Parse(txtDecimal1.Text)
                'converting to binary
                txtBinary1.Text = Convert.ToString(numConverter1D, 2)
                'converting to hex
                txtHex1.Text = Hex(numConverter1D)
    EndIf
    End Sub
    It's converting any decimal to binary and hex digits.

    Monday, March 19, 2018 9:50 PM
  • It's converting any decimal to binary and hex digits.

    You haven't indicated what the problem is.  You wanted a conversion to binary.  You have added a conversion to hex.  If you wanted the binary string formatted as per your first post then use the suggestion provided - pad left to 32 characters and insert the spaces every fourth character.   What is strFocused? that doesn't seem to be relevant to the problem.
    Monday, March 19, 2018 10:16 PM
  • I tried to use some of the suggestions you had but I am pretty sure it's my fault that I couldn't get them to work. IThis is the code I have,

    Private Sub btnConverter_Click(sender As Object, e As EventArgs) Handles btnConverter.Click
    
    If strFocused = "Decimal" And (Not txtDecimal1.Text = "") Then
                Dim numConverter1D As Integer = Integer.Parse(txtDecimal1.Text)
                'converting to binary
                txtBinary1.Text = Convert.ToString(numConverter1D, 2)
                'converting to hex
                txtHex1.Text = Hex(numConverter1D)
    EndIf
    End Sub

    So what problems are you having *exactly* when trying to use the
    suggestions? In the code you posted there is no evidence that you
    are trying to format the binary strings as desired.

    What happens when you try this using the function I posted?

    'converting to binary
    txtBinary1.Text = binformat(numConverter1D)
    

    - Wayne

    Monday, March 19, 2018 10:19 PM
  • sorry that's something else for the problem. It was just part of the sub, forgot to get it off. Thanks.
    Monday, March 19, 2018 10:23 PM
  • Hi Wayne, First I didn't have the systems.text namespace added so it wasn't working. I just tried it again and it's working great thank you so much. Much appreciated!!!
    Monday, March 19, 2018 10:30 PM
  • First I didn't have the systems.text namespace added so it wasn't working.
    You don't need to use a StringBuilder - in fact it will make your instructor suspicious about the source of your code.  A String is adequate for this task, but you will need to change the procedure so that you create the new string in code, rather than relying on the StringBuilder to do it for you.
        Function FormatBinary(ByVal num As Int32) As String
            Dim S As String = Convert.ToString(num, 2)
            S = S.PadLeft(32, "0"c)
            Dim T As String = ""
            For i = 0 To 31 Step 4
                T &= S.Substring(i, 4) & " "
            Next
            Return T
        End Function

    Tuesday, March 20, 2018 2:49 AM

  •     Function FormatBinary(ByVal num As Int32) As String
            Dim S As String = Convert.ToString(num, 2)
            S = S.PadLeft(32, "0"c)
            Dim T As String = ""
            For i = 0 To 31 Step 4
                T &= S.Substring(i, 4) & " "
            Next
            Return T
        End Function

    Just a trivial observation for the benefit of the OP.

    This code will result in an extra space character at the end of the
    string. While that will likely go unnoticed in the current context,
    if used in other programs with different output locations it might
    result in potentially confusing alignment issues.

    It can be removed easily enough via a trim if needed:

    'Return T
    Return T.TrimEnd(" "c)

    - Wayne

    Tuesday, March 20, 2018 4:31 AM
  •  Generic with different base support

        ''' <summary>
        ''' convert to formatted string
        ''' </summary>
        ''' <typeparam name="T"></typeparam>
        ''' <param name="num">the integral value to convert</param>
        ''' <param name="base">2, 8, 16</param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function ToStringInt(Of T)(num As T, Optional base As Integer = 2) As String
            If Not (base = 2 OrElse base = 8 OrElse base = 16) Then
                Return "" 'not valid base, maybe throw
            End If
            Dim L As Integer = 0
            Select Case True 'select length
                Case TypeOf num Is Int32
                    L = 32
                Case TypeOf num Is Int16
                    L = 16
                Case TypeOf num Is Int64
                    L = 64
                Case TypeOf num Is Byte
                    L = 8
                Case Else
                    Return "" 'not valid data type, maybe throw
            End Select
    
            Dim grp As Integer = 4 'grouping
    
            Select Case base
                Case 8 'octal is different, 3 bits per
                    If L = 8 Then L = 3
                    If L = 16 Then L = 6
                    If L = 32 Then L = 12
                    If L = 64 Then L = 24
                    grp = 3
                Case 16
                    L = L \ 4
                    If L = 2 Then grp = 2 'hex of byte
            End Select
    
            Dim n As Long = CLng(CTypeDynamic(num, GetType(Long)))
            Dim s As New System.Text.StringBuilder(Convert.ToString(n, base).PadLeft(L, "0"c))
            Dim rv As New System.Text.StringBuilder(s.Length * 2) 'return value
    
            Dim cpy(grp) As Char
            cpy(grp) = " "c
    
            For idx As Integer = 0 To s.Length - grp Step grp
                s.CopyTo(idx, cpy, 0, grp)
                rv.Append(cpy)
            Next
            Return rv.ToString.Trim
    
        End Function


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it" - MSDN User JohnWein


    • Edited by dbasnett Tuesday, March 20, 2018 5:18 PM
    Tuesday, March 20, 2018 1:50 PM