I can\'t find the answer to my specific problem anywhere so I figured I\'d open a new question.
I have a program that converts text between ASCII and Binary. It does thi
There's an easier way to do it:
Function BinaryStringToAscii(s As String) As String
If s.Length Mod 8 <> 0 Then
Throw New ArgumentException("String length is not a multiple of 8.")
End If
Dim sb As New Text.StringBuilder
For i = 0 To s.Length - 1 Step 8
Dim bin = s.Substring(i, 8)
sb.Append(Chr(Convert.ToInt32(bin, 2)))
Next
Return sb.ToString()
End Function
It uses a StringBuilder as in the end you need a string, and there is no need to use an array or list. The Convert.ToInt32 function has a useful overload where you can specify the base (2, 8, 10 or 16) to convert a string from.
And the converse:
Function AsciiToBinaryString(s As String) As String
Dim sb As New Text.StringBuilder
For Each c In s
sb.Append(Convert.ToString(Asc(c), 2).PadLeft(8, "0"c))
Next
Return sb.ToString()
End Function
You've declared an array, result
, but the variable hasn't been assigned an instance of an array, so it's null. You can't add objects to a null array. Perhaps you meant this:
Dim result(BinarySubstrings.Length) As String
If you aren't sure about the size of result, consider using a List(Of String)
as mentioned in the comments.
Using a List(Of String) is better because you don't need to know the size of the array.
Of course you need to initialize the List(Of String) before usage.
Function ConvertBinaryToASCII(ByVal input As String) As String
Dim ASCIIList() As String = .....
Dim BinaryList() As String = ......
Dim BinarySubstrings = Enumerable.Range(0, input.Length \ 8).[Select](Function(i) input.Substring(i * 8, 8)).ToArray()
Dim result = new List(Of String)()
Dim binaryMatch As Integer
For Each e As String In BinarySubstrings
binaryMatch = Array.IndexOf(BinaryList, e)
result.Add(ASCIIList(CInt(binaryMatch)))
Next
Return String.Join("", result.ToArray())
End Function