0
votes
BigInteger b = new BigInteger("-5");
System.out.println(b.toString(2));

prints

-101

I would like to get two's complement binary code on a given number of bits instead of positive binary string with a - sign.

For instance

BigInteger b = new BigInteger("-5");
System.out.println(b.toString(2, 4));//-5 on 4 bits in binary code

should display

1011

and

BigInteger b = new BigInteger("-5");
System.out.println(b.toString(2, 5));//-5 on 4 bits in binary code

should display

11011
1

1 Answers

1
votes

As far as I know BigInteger this does not exist. You need to build such a method on your own.

String toString(BigInteger bigInt, int bits){
    StringBuilder sb = new StringBuilder();
    for(int bit = bits - 1; bit >= 0; bit--)
        if(BigInteger.valueOf(1 << bit).and(bigInt).compareTo(BigInteger.ZERO) != 0)
            sb.append("1");
        else
            sb.append("0");       
    return sb.toString();
}