0

My question might be so basic but I'm still asking this. I reffered this post and what I understood in the logical & does bitwise AND 0101 & 0011 = 0001 Is there any usecases where we can apply & on decimal numbers? For example , if you consider logical ^ (XOR) , it is useful to find unique number in an array, where all the other elements present twice.

Eg: if you have an array [1,1,2,2,3,3,4,4,6,6,7] and you need to get 7

    int[] x = new int[]{1,1,2,2,3,3,4,4,6,6,7};
    int y = x[0];
    for (int i = 1; i < x.length; i++) {
        y ^= x[i];
    }
    System.out.println(y);

This code will give the result quickly, Similarly is there any usage of & in such usecases?

user3339689
  • 105
  • 1
  • 7
  • 1
    It's hard to work out what you're asking here. You ask about decimal numbers, but your example uses `int` (not `double` or `float`). You link to a C# question rather than a Java question. (They're different languages and the semantics overlap, but aren't the same.) But just a quick note on terminology: `&`, `|`, and `^` aren't *logical* operators unless they're applied to a `boolean` ([spec](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.22)). When applied to other types, they're *bitwise* operators. – T.J. Crowder Dec 10 '18 at 07:44

1 Answers1

1

There is no such thing as "apply & on decimal numbers". Numeric values are stored in binary in the computer. The default printing of numeric values is in decimal format, but that's just intended to make them human readable.

As for example for using & (bit-wise AND) on ints, when you have an int bit-mask (in which each bit represents something), you can use bit-wise AND to determine the value of any specific bit.

For example:

int mask = 13;
if (mask & 2 > 0) { // this tests if the 2nd lowest bit of mask is 1

}
if (mask & 4 > 0) { // this tests if the 3nd lowest bit of mask is 1

}
Eran
  • 387,369
  • 54
  • 702
  • 768