Search code examples
vb.netbinarysubtraction

Binary Subtraction VB.NET


I would like to ask some help about Binary Subtraction in Visual Basic 2010 .My code works well, thanks to @video.baba

Dim BinaryResult As Integer = Convert.ToInt32(TextBox1.Text, 2) + Convert.ToInt32(TextBox2.Text, 2)
Textbox3.Text = BinaryResult.ToString

eventually, the problem is this. If the 1st input is lower from the 2nd input that gives me a result of negative but the answer is so far away

Example :

0000 - 1111 = 11111111111111111111111111111001 

MUST BE

0000 - 1111 = -01111

Any help would be appreciated. Thanks


Solution

  • If you really want the output to be -01111 (or -1111, since the leading zero is omitted) you have to make the number positive and then prepend the binary string with the minus sign.

    Then, when converting it back you have to remove the sign and make the resulting number negative again.

    Converting to binary:

    Dim BinaryResult As Integer = Convert.ToInt32(TextBox1.Text, 2) - Convert.ToInt32(TextBox2.Text, 2)
    
    If BinaryResult < 0 Then
        TextBox3.Text = "-" & Convert.ToString(-BinaryResult, 2)
    Else
        TextBox3.Text = Convert.ToString(BinaryResult, 2)
    End If
    

    Converting from binary:

    Dim BinaryResult As Integer
    
    If TextBox3.Text.StartsWith("-") Then
        BinaryResult = -Convert.ToInt32(TextBox3.Text.TrimStart("-"c), 2)
    Else
        BinaryResult = Convert.ToInt32(TextBox3.Text, 2)
    End If
    

    Reusable version:

    Private Function BinarySubtract(ByVal a As String, ByVal b As String) As String
        Dim BinaryResult As Integer = Convert.ToInt32(a, 2) - Convert.ToInt32(b, 2)
        If BinaryResult < 0 Then
            Return "-" & Convert.ToString(-BinaryResult, 2)
        Else
            Return Convert.ToString(BinaryResult, 2)
        End If
    End Function
    
    Private Function FromBinary(ByVal s As String) As Integer
        If s.StartsWith("-") Then
            Return -Convert.ToInt32(s.TrimStart("-"c), 2)
        Else
            Return Convert.ToInt32(s, 2)
        End If
    End Function
    

    Online test: https://dotnetfiddle.net/PoQZA6