Display a value in Binary

How would I display a number in binary format. I looked through the help files and only found how to display in hex format. I am making a small bitwise calculator for personal use and need to display value in binary format. Thanks.



Answer this question

Display a value in Binary

  • rwlavoie

    Ok, thanks for that. It worked but is there a newer method Also, is there a way to make the binary value only as long as it needs to be instead of being a long at all times (If the integer is 5 then I want the bin to say 101 instead of 00000000000000000000000000000101. I tried the trim method but it didn't work.


  • zdux0012

    convert to string can do it:

    dim s as string = Convert.ToString(100, 2)

    output: 1100100

  • mrichards0

    Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    TextBox1.AcceptsReturn = True

    End Sub

    Sub Text1_Change()

    Dim i As Long, x As Long, bin As String

    Const maxpower = 30 ' Maximum number of binary digits supported.

    TextBox1.MaxLength = 9 ' Maximum number of decimal digits allowed.

    bin = "" 'Build the desired binary number in this string, bin.

    x = Val(TextBox1.Text) 'Convert decimal string in text1 to long integer

    ' Here is the heart of the conversion from decimal to binary:

    ' Negative numbers have "1" in the 32nd left-most digit:

    If x < 0 Then bin = bin + "1" Else bin = bin + "0"

    For i = maxpower To 0 Step -1

    If x And (2 ^ i) Then ' Use the logical "AND" operator.

    bin = bin + "1"

    Else

    bin = bin + "0"

    End If

    Next

    For i = 0 To bin.Length - 1

    If bin.Substring(i, 1) <> "0" Then

    TextBox1.Text = bin.Substring(i)

    Exit Sub

    End If

    Next

    TextBox1.Text = bin ' The bin string contains the binary number.

    End Sub

    Private Sub Textbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    'The following properties must be set thusly:

    If e.KeyChar = Chr(Keys.Enter) Then

    Text1_Change()

    e.Handled = True

    End If

    End Sub

    End Class



  • TannerH

  • Display a value in Binary