Microsoft Small Basic

Program Listing: JKH581
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.Title = "Text to Binary : Binary to Text"

TextBox = Controls.AddMultiLineTextBox(10,10)
Controls.SetSize(TextBox,380,250)
ButtonTB = Controls.AddButton("Convert to Binary",10,265)
ButtonBT = Controls.AddButton("Convert to Text",140,265)
Controls.ButtonClicked = onClick

Sub onClick
LastButton = Controls.LastClickedButton
If LastButton = "Button1" Then
ConvertToBinary()
Else
ConvertToText()
EndIf
EndSub
Sub ConvertToBinary
String = Controls.GetTextBoxText(TextBox)
For i = 1 To Text.GetLength(String)
CharCode = Text.GetCharacterCode(Text.GetSubText(String,i,1))
'convert ascii codes into binary
bit = ""
binval = ""
Count = 0
While CharCode > 0
bit[Count] = Math.Remainder(CharCode,2)
CharCode = Math.Floor(CharCode / 2)
Count = Count + 1
EndWhile
For j = Array.GetItemCount(bit) To 0 Step -1
binval = Text.Append(binval,bit[j])
EndFor
'add leading zero to make binary value even
For b = 0 To 8 - Text.GetLength(binval)
binval = Text.Append(0,binval)
EndFor
longbin = Text.Append(longbin,binval)
EndFor
Controls.SetTextBoxText(TextBox,longbin)
longbin = ""
EndSub
Sub ConvertToText
Binary = Controls.GetTextBoxText(TextBox)
If Math.Remainder(Text.GetLength(Binary),8) <> 0 Then
GraphicsWindow.ShowMessage("Binary is un even","Error")
Else
For g = 1 To Text.GetLength(Binary) Step 8
Binarychar = Text.GetSubText(Binary,g,8)
'Convert binary to decimal
For bit_Count = 1 To Text.GetLength(Binarychar)
binaryNum = binaryNum + Text.GetSubText(Binarychar,Text.GetLength(Binarychar)-bit_Count+1,1)*Math.Power(2,bit_Count-1)
EndFor
'get char from ascci code
Char = Text.GetCharacter(binaryNum)
binaryNum = ""
'append char
LongString = Text.Append(LongString,Char)
EndFor
Controls.SetTextBoxText(TextBox,LongString)
LongString = ""
EndIf
EndSub