I want to convert an octal number to binary for purposes related to my avionics (transponders to be specific). I do vb.net in my spare time, learning on my own. But for this, I'm not sure how to do it, even after googling.
Here is how I have it set up so far: form1
Here's all the code I have so far. This is so only numers 1-7 can be entered:
Public Class Form1
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 55 Then
e.Handled = True
End If
End If
End Sub
End Class
I'm not sure how to convert Textbox1.text into binary and then separate it into the following textboxes for A,B,C,D.
Ex: You have A4, A2, and A1 (the 000). Those add to 7 (111). This is repeated for B,C, and D.
So to sum things up, I want to convert the octal number into binary and, if I can, separate it into separate boxes corresponding to the letters.
This is how it should look (can't post more than 2 links): 2134 = A4,2,1(010) B4,2,1(001) C4,2,1(011) D4,2,1(100)
Edit: I have tried Convert.ToString(#NUMBER, 2) but it returns the wrong binary code. 7631 returns 1110111001111 but it should be 111110011001. See http: //ncalculators.com/digital-computation/binary-octal-converter.htm
To convert an octal string to a binary string:
Private Function OctToBin(octal As String) As String
Return Convert.ToString(Convert.ToInt32(octal, 8), 2)
End Function
To convert a binary string into an array of three-character substrings:
Private Function ToBinBytes(binary As String) As String()
Dim chars = binary.Reverse().ToArray()
Dim binBytes As New List(Of String)
Do While chars.Length > 0
Dim byteChars = chars.Take(3).Reverse().ToArray()
binBytes.Add(New String(byteChars).PadLeft(3, "0"c))
chars = chars.Skip(3).ToArray()
Loop
Return binBytes.AsEnumerable().Reverse().ToArray()
End Function
Both are untested but I think they're right.
Tested with this code:
Dim n = 1234567
Dim o = Convert.ToString(n, 8)
Dim b = OctToBin(o)
MessageBox.Show((n = Convert.ToInt32(b, 2)).ToString())
MessageBox.Show(String.Join(Environment.NewLine, ToBinBytes(b)), b)