Here's my version:
Full Codes:
The cleaner, the better.
Full Codes:
Code:
Imports System.Text
Imports System.Text.RegularExpressions
Public Class Form1
'String to Binary
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
RichTextBox2.Text = TextToBinary(RichTextBox1.Text)
End Sub
'Binary to string
Private Sub Button6_Click(sender As System.Object, e As System.EventArgs) Handles Button6.Click
RichTextBox1.Text = BinaryToText(RichTextBox2.Text)
End Sub
'Clear string to binary RichTextBox
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
RichTextBox1.Clear()
End Sub
''Clear binary to string RichTextBox
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
RichTextBox2.Clear()
End Sub
'Clipboard string to binary RichTextBox
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
If RichTextBox1.SelectedText <> "" Then
Clipboard.SetDataObject(RichTextBox1.SelectedText)
End If
End Sub
'Clipboard binary to string RichTextBox
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
If RichTextBox2.SelectedText <> "" Then
Clipboard.SetDataObject(RichTextBox2.SelectedText)
End If
End Sub
'Only allow 0 and 1 in binary to string RichTextBox
Private Sub RichTextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox2.KeyPress
If e.KeyChar < "0" Or e.KeyChar > "1" Then
MessageBox.Show("Only binary digits allowed.")
e.Handled = True
Else
RichTextBox1.Text = BinaryToText(RichTextBox2.Text)
End If
End Sub
' Conversion to Binary
Private Shared Function TextToBinary(ByVal Text As String, Optional ByVal Separator As String = " ") As String
Try
Dim oReturn As New StringBuilder
' Convert to ASCII and go through all the bytes
For Each Character As Byte In ASCIIEncoding.ASCII.GetBytes(Text)
oReturn.Append(Convert.ToString(Character, 2).PadLeft(8, "0"))
oReturn.Append(Separator)
Next
Return oReturn.ToString
Catch ex As Exception
Return ex.Message
End Try
End Function
'Conversion to Text
Private Shared Function BinaryToText(ByVal BinaryText As String) As String
Try
Dim Characters As String = Regex.Replace(BinaryText, "[^01]", "")
Dim ByteArray((Characters.Length / 8) - 1) As Byte
' Retrieve the original byte array
For Index As Integer = 0 To ByteArray.Length - 1
ByteArray(Index) = Convert.ToByte(Characters.Substring(Index * 8, 8), 2)
Next
' Convert the ASCII-array to a Unicode string
Return ASCIIEncoding.ASCII.GetString(ByteArray)
Catch ex As Exception
Return ex.Message
End Try
End Function
End Class
The cleaner, the better.