-3

I have this code:

if ((x & y)==0){ 
// do this... 
}

I would like to achieve the same effect but using BigInteger instead of int.

I tried this:

if ((x.compareTo(BigInteger.ZERO)==0)&&(y.compareTo(BigInteger.ZERO)==0)){ 
// do this...
}

Now, however, my program is never going inside this if statement. I would really appreciate your help.

Also, here's the entire code.

import java.math.*;

public class mew {

public static void main (String[] args) {

BigInteger two = BigInteger.valueOf(2);
BigInteger num = two.pow(100);
BigInteger i = BigInteger.valueOf(0);

while (i.compareTo(num) < 0){
    BigInteger mask = num;

    while (mask.compareTo(BigInteger.ZERO) > 0){
            if ((mask.compareTo(BigInteger.ZERO)==0)&&(i.compareTo(BigInteger.ZERO)==0)){
             System.out.print("0");
             }
            else {
             System.out.print("1");
                }
             mask = mask.shiftRight(1);
                }
     System.out.println();
     i = i.add(BigInteger.valueOf(1));
          }

    }
}

The purpose is to print all possible permutations of an n-long bit string. I ought to reference where I got the idea and the implementation: Java: How to output all possible binary combinations (256 different sequences)? see nikis post.

Community
  • 1
  • 1
Novice
  • 613
  • 1
  • 5
  • 17
  • 3
    `int&int` is a bitwise operator, **not** a logical operator. Its equivalent is [`BigInteger.and(BigInteger)`](http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#and(java.math.BigInteger)) – khelwood Oct 30 '15 at 20:23
  • 4
    `x & y == 0` does *not* mean `x == 0 && y == 0`. – Erick G. Hagstrom Oct 30 '15 at 20:24
  • Takeaway: read the JavaDoc. – Erick G. Hagstrom Oct 30 '15 at 20:26
  • Your expression using `BigInteger` isn't equivalent to your original `if ((x & y) == 0)`. The `(x & y) == 0` is **true** if `x` and `y` don't have any 1 bits in common in their binary representations. But your `BigInteger` expression is true if both the mask and the value are zero, which evidently never happens. – lurker Oct 30 '15 at 20:26

1 Answers1

5

The equivalent of

if ((x & y)==0){ 
    // do this... 
}

for BigInteger is

if (x.and(y).equals(BigInteger.ZERO)) {
    // do this...
}

Neither of these things is the same as saying "if x and y are both zero".

sjr
  • 9,769
  • 1
  • 25
  • 36