Please refer this code
I have given input in 4 bits form
HTML:
<form id="form1" runat="server">
<div>
Enter 4 bit Binary number
<asp:TextBox ID="txtBinaryNumber" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="GenerateComp" Text="Generate 1's and 2's Complements" />
<br />
1's Complement
<asp:Label ID="lblOnesComplement" runat="server" />
<br />
2's Complement
<asp:Label ID="lblTwosComplement" runat="server" />
</div>
</form>
VB:
Protected Sub GenerateComp(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim bits As String = Me.txtBinaryNumber.Text
Dim onceComplement As String = String.Empty
For i As Integer = 0 To bits.Length - 1
onceComplement += If(bits(i) = "0"c, "1", "0")
Next
Dim twosComplement As String = String.Empty
Dim carry As String = "0"
Dim lastPosition As Integer = onceComplement.Length
Dim ch As String = onceComplement.ElementAt(lastPosition - 1).ToString()
If ch = "0" Then
twosComplement = onceComplement.Substring(0, lastPosition - 1) + "1"
Else
For i As Integer = 0 To onceComplement.Length - 1
ch = onceComplement.ElementAt(lastPosition - 1).ToString()
If ch = "1" AndAlso carry = "1" Then
twosComplement += "0"
carry = "1"
ElseIf ch = "0" AndAlso carry = "0" Then
twosComplement += onceComplement.ElementAt(lastPosition - 1).ToString()
ElseIf ch = "0" AndAlso carry = "1" Then
twosComplement += "1"
carry = "0"
ElseIf ch = "1" AndAlso carry = "0" Then
twosComplement += "1"
carry = "1"
End If
lastPosition -= 1
Next
End If
Me.lblOnesComplement.Text = onceComplement
Me.lblTwosComplement.Text = twosComplement
End Sub
Using C#:
protected void GenerateComp(object sender, EventArgs e)
{
string bits = this.txtBinaryNumber.Text.Trim();
string onceComplement = string.Empty;
for (int i = 0; i < bits.Length; i++)
{
onceComplement += bits[i] == '0' ? "1" : "0";
}
string twosComplement = string.Empty;
string carry = "0";
int lastPosition = onceComplement.Length;
string ch = onceComplement.ElementAt(lastPosition - 1).ToString();
if (ch == "0")
{
twosComplement = onceComplement.Substring(0, lastPosition - 1) + "1";
}
else
{
for (int i = 0; i < onceComplement.Length; i++)
{
ch = onceComplement.ElementAt(lastPosition - 1).ToString();
if (ch == "1" && carry == "1")
{
twosComplement += "0";
carry = "1";
}
else if (ch == "0" && carry == "0")
{
twosComplement += onceComplement.ElementAt(lastPosition - 1).ToString();
}
else if (ch == "0" && carry == "1")
{
twosComplement += "1";
carry = "0";
}
else if (ch == "1" && carry == "0")
{
twosComplement += "1";
carry = "1";
}
lastPosition--;
}
}
this.lblOnesComplement.Text = onceComplement;
this.lblTwosComplement.Text = twosComplement;
}
Image:
Thank You.