# Bits Manipulation in Java

By | April 29, 2017

## 1. Detect if two integers have opposite signs.

```/* Using XOR operator
*  Examples: isOppositeSigns(4, -5) = true;
*            isOppositeSigns(4, 5) = false;
*/
boolean isOppositeSigns(int x, int y) {
return ((x ^ y) < 0);
}
```

## 2. Determining if an integer is a power of 2.

```/* Note that 0 is incorrectly considered a power of 2
*  Examples: isPowerOfTwo(4) = true; isPowerOfTwo(3) = false;
*/
boolean isPowerOfTwo(int v) {
return (v & (v -1 )) == 0;
}
```

## 3. Swap the values of a and b without using a temporary variable.

```    // Swapping values with XOR
int a = 10, b = 9;
a ^= b;
b ^= a;
a ^= b;
```

## 4. Check non-zero.

```/*
* isNonZero - Check whether x is nonzero
* Examples: isNonZero(3) = 1, isNonZero(0) = 0
*/
int isNonZero(int x) {
/* 0 is special since negating it returns same number
* (and thus both have 0 sign bit).
* Shift sign bits, OR them, and mask against 1 to see
* if either had a 1 sing bit
*/
int n = ~x + 1;
return ((n >> 31) | (x >> 31)) & 1;
}
```

References:

This site uses Akismet to reduce spam. Learn how your comment data is processed.