27

Can we convert Biginteger to binary string

   String s1 = "0011111111101111111111111100101101111100110000001011111000010100";
   String s2 = "0011111111100000110011001100110011001100110011001100110011001100";
   BigInteger bi1, bi2, bi3;
   bi1 = new BigInteger(s1,2);
   bi2 = new BigInteger(s2,2);
   bi3 = bi1.xor(bi2);

How to convert bi3 to binary string

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Kailash
  • 642
  • 2
  • 9
  • 15

2 Answers2

48

You can use toString(radix) for that:

String s3 = bi3.toString(2);
TT.
  • 15,774
  • 6
  • 47
  • 88
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

import java.math.BigInteger; import java.util.Scanner;

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a Number: ");
    String n = in.next();
    BigInteger nn = new BigInteger(n);
    if(nn.compareTo(BigInteger.ZERO)<0){
        System.out.println("Number cannot be less than 0");
    }else{
        System.out.println("Convert to binary is:");
        print2Binaryform(nn);
        System.out.println("");
    }
}
private static void print2Binaryform(BigInteger number) {
    BigInteger reminder2;
    if(number.compareTo(BigInteger.ONE)<=0){
        System.out.print(number);
        return;
    }
    reminder2 = number.mod(new BigInteger(""+2));
    print2Binaryform(new BigInteger(""+number.divide(new BigInteger("2"))));
    System.out.print(reminder2);
}
  • Hi Riven. In what way do you think your answer is better than the one dasblinkenlight posted? (His answer is a one-liner: `nn.toString(2);`) – TT. Oct 03 '18 at 16:38
  • Oh, honestly, my code is too much larger, but i think it represents the logic better and it could be implemented in more ways by customizing it. – Riven Flows Oct 05 '18 at 05:11
  • for example, you could change to conver decimal to base-n – Riven Flows Oct 05 '18 at 05:13
  • Hi again Riven. That is what the `BigInteger.toString( int radix )` method is for, exactly for converting to base-n (n being the radix). – TT. Oct 05 '18 at 09:23