4

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.

9
  • Do you know the theory behind it? If you know the theory, implementing it is an easy task. What have you tried so far? Commented Mar 4, 2017 at 12:24
  • This possibly pure Java.. How is it specific to Android? Commented Mar 4, 2017 at 12:25
  • @BackSlash I have posted my code to get 1's complement. Commented Mar 4, 2017 at 12:34
  • @suraj Android uses core Java itself. Commented Mar 4, 2017 at 12:44
  • 1
    Possible duplicate of How to convert ones' complement number into its 2's complement? Commented Mar 4, 2017 at 13:04

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;

3 Comments

Also, without finding the 1's complement first: go through the original binary string backwards, if you find a 1 flip all other numbers after that 1.
@BackSlash - I think this comment is a saver. Can you please explain the math behind this?
@BhanuDevapatla It's simple logic :) 2's complement is: NOT(original) + 01. So, for 0001, it is NOT(0001) + 01 = 1110 + 01 = 1111. For 0010 it's NOT(0010) + 01 = 1101 + 01 = 1110. For 0011 it's NOT(0011) + 01 = 1100 + 01 = 1101. For 1111 it's NOT(1111) + 01 = 0000 + 01 = 0001. If you watch closely you'll notice that this is the same of 1) reading the number from right to left, 2) keeping the bits until you find a 1, 3) negating all other bits (0 becomes 1, 1 becomes 0).
1

I was doing some browsing on this subject and ended up reading this question and its answers. The way I see it, there is this much simpler way to calculate the two's complement of a integer.

public static int twosComplement(final int value) {
    final int mask = 0xffff_ffff;
    return (value ^ mask) + 1;
}

public static String stringTwosComplement(String bin) {
    int value = Integer.parseInt(bin, 2);
    int result = twosComplement(value);
    return Integer.toBinaryString(result);
}

The algorithm is based on the same idea @malte-hartwig brought in his answer: the two's complement is the one's complement plus 1.

Comments

0

@BackSlash's comment above is intriguing. This answer is the full program written based on this idea:

import java.time.temporal.ValueRange;
import java.util.Scanner;

//This program generates convert decimal to binary
public class ConvertDecimalToBinary {


    public static int getNumberOfBytes(int n) {
        int bytes = 0;
        ValueRange byteRange = ValueRange.of(Byte.MIN_VALUE, Byte.MAX_VALUE);
        ValueRange shortRange = ValueRange.of(Short.MIN_VALUE, Short.MAX_VALUE);
        ValueRange intRange = ValueRange.of(Integer.MIN_VALUE, Integer.MAX_VALUE);
        if (byteRange.isValidValue(n)) {
            bytes = 1;
        } else if (shortRange.isValidValue(n)) {
            bytes = 2;
        } else if (intRange.isValidValue(n)) {
            bytes = 4;
        }
        return bytes;
    }

    //Convert a positive decimal number to binary
    public static String convertPositiveNumberToBinary(int n, int bytes,boolean reverse) {
        int bits = 8 * bytes;
        StringBuilder sb = new StringBuilder(bits); //in-bits
        if (n == 0) {
            sb.append("0");
        } else {
            while (n > 0) {
                sb.append(n % 2);
                n >>= 1;  //aka n/2
            }
        }

        if (sb.length() < bits) {
            for (int i = sb.length(); i < bits; i++) {
                sb.append("0");

            }
        }
        if (reverse) {
            return sb.toString();
        } else {
            return sb.reverse().toString();
        }
    }

    //Convert negative decimal number to binary
    public static String convertNegativeNumberToBinary(int n, int bytes) {
        int m = -n; //conver to positve
        String binary = convertPositiveNumberToBinary(m,bytes,true);
        int len = binary.length();
        StringBuilder sb = new StringBuilder(len); //in-bits
        boolean foundFirstOne = false;
        for(int i=0; i < len;i++) {
            if(foundFirstOne)  {
                if(binary.charAt(i) == '1') {
                    sb.append('0');
                }
                else {
                    sb.append('1');
                }
            }
            else {
                if(binary.charAt(i) == '1') {
                    foundFirstOne = true;
                }
                sb.append(binary.charAt(i));
            }
        }
        return sb.reverse().toString();

    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextInt()) {
            int n = scanner.nextInt();
            int bytes = getNumberOfBytes(n);
            String binary;

            if(n >= 0) {
                binary = convertPositiveNumberToBinary(n,bytes,false);
            }
            else {
                binary = convertNegativeNumberToBinary(n,bytes);
            }
            System.out.println(String.format("Binary representation of {%s} is {%s}",n,binary));
        }
        scanner.close();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.