How to make a simple tool that converts Text to Binary

Heres your chance to share your own tutorials with the community. Just post them on here. If your lucky they may even be posted on the main site.
2 posts Page 1 of 1
Contributors
Vikhedgehog
VIP - Donator
VIP - Donator
Posts: 812
Joined: Fri Nov 05, 2010 6:24 pm

Did you ever need to convert Text to Binary? Of course it is very easy to find one and download it. But what about making your own one! Follow these steps to get it to work. First create two textboxes and one button. Set the property of TextBox2 to "ReadOnly". Call the button "Convert!" If the user presses the button the text in the first textbox will be displayed in the second textbox - just in binary! You don't need to import any things, just double click the button and type:
Code: Select all
Dim Val As String = Nothing
        Dim Result As New System.Text.StringBuilder
        For Each Character As Byte In System.Text.ASCIIEncoding.ASCII.GetBytes(TextBox1.Text)
            Result.Append(Convert.ToString(Character, 2).PadLeft(8, "0"))
            Result.Append(" ")
        Next
        Val = Result.ToString.Substring(0, Result.ToString.Length - 1)
        TextBox2.Text = Val
That's all. Congrats! clapper;

P.S. There is no working code to convert Binary to Text. If i'll find it i'll post it.
User avatar
mandai
Coding God
Coding God
Posts: 2585
Joined: Mon Apr 26, 2010 6:51 pm

I'd use these functions:
Code: Select all
    Function getBinaryFromString(ByVal input As String) As String

        Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(input)
        Dim bits As BitArray = New BitArray(bytes)

        Dim time As Integer = 0
        Dim output As String = ""
        For i As Integer = 0 To bits.Length - 1
            time += 1
            Dim temp As Byte = Convert.ToInt32(bits(i))
            output += temp.ToString()
            If time = 8 And Not i = bits.Length - 1 Then
                time = 0
                output += " "
            End If
        Next
        Return output
    End Function

    Function getStringFromBinary(ByVal input As String) As String

        Dim strbytes As String() = input.Split(" "c)

        Dim bits As BitArray = New BitArray(strbytes.Length * 8)

        Dim bitpos As Integer = 0
        For i As Integer = 0 To strbytes.Length - 1
            For i2 As Integer = 0 To 7
                bits(bitpos) = strbytes(i)(i2).ToString()
                bitpos += 1
            Next
        Next

        Dim bytes(strbytes.Length - 1) As Byte
        bits.CopyTo(bytes, 0)

        Dim output As String = Encoding.ASCII.GetString(bytes)

        Return output
    End Function
2 posts Page 1 of 1
Return to “Tutorials”