Write a program to find 2s complement of a Binary number in java


The code is an implementation of a method to obtain the two's complement of a binary number represented as a string. The main method calls the twosCompliment method, passing a binary number "01101100" as a string. The twosCompliment method then performs the following steps:

  • Creates two strings, ones and twos, initially empty.
  • Iterates over each character in the input binary string and flips it using the flip method (which returns '1' if the input is '0', and '0' if the input is '1'), and appends the result to the ones string.
  • Converts the ones string to an integer using parseInt method and assigns it to the variable number0.
  • Creates a StringBuilder object with the ones string and assigns it to the variable builder.
  • Iterates over each character in the ones string in reverse order, starting from the second to last character, and performs the following steps:
    • If the current character is '1', set the corresponding character in the builder to '0'.
    • Otherwise, set the corresponding character in the builder to '1', and set the boolean variable b to true.
    • If b is true, break out of the loop.
  • If b is false, append the string "1" to the builder from position 0 to 7.
  • Converts the builder to a string and assigns it to the variable twos.
  • Returns the twos string.

Finally, the twosCompliment method returns the two's complement of the input binary string as a string, which is printed to the console by the main method.

Source Code

class Twos_Compliment
{
	public static void main(String args[])
	{
		System.out.print(twosCompliment("01101100"));
	}
	public static String twosCompliment(String bin) {
        String twos = "", ones = "";
 
        for (int i = 0; i < bin.length(); i++) {
            ones += flip(bin.charAt(i));
        }
        int number0 = Integer.parseInt(ones, 2);
        StringBuilder builder = new StringBuilder(ones);
        boolean b = false;
        for (int i = ones.length() - 1; i > 0; i--) {
            if (ones.charAt(i) == '1') {
                builder.setCharAt(i, '0');
            } else {
                builder.setCharAt(i, '1');
                b = true;
                break;
            }
        }
        if (!b)
            builder.append("1", 0, 7);
 
        twos = builder.toString();
 
        return twos;
    }
 
    public static char flip(char c) {
        return (c == '0') ? '1' : '0';
    }
}

Output

10010100

Example Programs