2

I have to find the twos Complement of a decimal number. The input is in Byte and the result should be in String. I have already written a program that converts decimal to binary but i don't know how to convert binary String to ones Complement aka replacing 0 with 1 and 1 with 0.

This is what I have written so far:

String toTwoComp(byte n) {
    String s = "";
    byte num = n;
    String res = "";
    while (n > -128 && n < 127) {
        s = (num % 2) + s;
        num = (byte) (num / 2);
        if (num == 0) {
            break;
        }
    }
    res = "00000000".substring(s.length()) + s;
    return res;
}
Curiosa Globunznik
  • 3,129
  • 1
  • 16
  • 24
nsol
  • 75
  • 7

1 Answers1

0

Two's complement of any byte or int x is just -x. So did you try this?

   String b = toTwosComp((byte)3);
   System.out.println(b);


   static String toTwosComp(byte n) {
      int twosComp = -n;
      return Integer.toBinaryString(twosComp & 0xFF);
   }

Note that you can do this and just use your own method to convert to a binary string.

WJS
  • 36,363
  • 4
  • 24
  • 39
  • this is a homework and unfortunately i am not allowed to use 'Integer.toBinaryString(( & 0xFF) + 256).substring(1)' – nsol Nov 17 '19 at 19:03
  • Then just use your own method to convert decimal to a binary string. You said that already worked. – WJS Nov 17 '19 at 19:21
  • how do I convert a binary string to ones complement? – nsol Nov 17 '19 at 20:10