Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 2's complement of a binary number in Java programmatically

How to calculate the 2's Complement of a Hex number in Android/Java.

    For Example : 
    String x = 10011010;
    1's complement of x = 01100101;
    2's complement is 01100110;

How I can pro-grammatically achieve in Java?

I had tried the following code to convert the binary to its 1's compliment:

public String complementFunction(String bin) {
        String  ones = "";

        for (int i = 0; i < bin.length(); i++) {
            ones += flip(bin.charAt(i));
        }
        return ones;
    }

// Returns '0' for '1' and '1' for '0'
    public char flip(char c) {
        return (c == '0') ? '1' : '0';
    }

But I'm not able to get its two's complement.

like image 675
Sarbjit Singh Avatar asked Sep 02 '25 09:09

Sarbjit Singh


2 Answers

Thanks for your help everyone. I got the solution and it is as follows :

  public 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;
    }

// Returns '0' for '1' and '1' for '0'
    public char flip(char c) {
        return (c == '0') ? '1' : '0';
    }

Thanks to all for helping.

like image 200
Sarbjit Singh Avatar answered Sep 05 '25 00:09

Sarbjit Singh


This wikipedia section explains an easy way to get the 2's complement: Get the 1's complement, then add 1 (in binary logic). So you can use the complementFunction you already have, then go through the String backwards. If you find a 1, flip it and continue. If you find a 0, flip it and stop.

String  twos = "";
for (int i = bin.length() - 1; i >= 0; i--) {
    if (bin.charAt(i) == '1') {
        twos = "0" + twos;
    } else {
        twos = bin.substring(0, i) + "1" + two;
        break;
    }
    twos = flip(bin.charAt(i));
}
return twos;
like image 25
Malte Hartwig Avatar answered Sep 05 '25 00:09

Malte Hartwig