Examples of Bitwise Operator Application
char v1 = ‘)’; // Unicode value 41
byte v2 = 13;
int result1 = ~v1; // -42
int result2 = v1 & v2; // 9
int result3 = v1 | v2; // 45
int result4 = v1 ^ v2; // 36
Table 2.32 shows how the result is calculated. Unary and binary numeric promotions are applied first, converting the operands to int in these cases. Note that the operator semantics are applied to corresponding individual bits—that is, the first bit of the left-hand operand and the first bit of the right-hand operand, the second bit of the left-hand operand and the second bit of the right-hand operand, and so on.
Table 2.32 Examples of Bitwise Operations
~v1 | v1 & v2 | v1 | v2 | v1 ^ v2 |
~ 0…0010 1001 | 0…0010 1001 | 0…0010 1001 | 0…0010 1001 |
& 0…0000 1101 | | 0…0000 1101 | ^ 0…0000 1101 | |
= 1…1101 0110 | = 0…0000 1001 | = 0…0010 1101 | = 0…0010 0100 |
= 0xffffffd6 | = 0x00000009 | = 0x0000002d | = 0x00000024 |
= -42 | = 9 | = 45 | = 36 |
It is instructive to run examples and print the result of a bitwise operation in different notations, as shown in Example 2.4. The integer bitwise operators support a programming technique called bit masking. The value v2 is usually called a bit mask. Depending on the bitwise operation performed on the value v1 and the mask v2, we see how the resulting value reflects the bitwise operation performed between the individual corresponding bits of the value v1 and the mask v2. By choosing appropriate values for the bits in the mask v2 and the right bitwise operation, it is possible to extract, set, and toggle specific bits in the value v1.
Methods for converting integers to strings in different notations can be found in the Integer class (§8.3, p. 435).
Example 2.4 Bitwise Operations
public class BitOperations {
public static void main(String[] args) {
char v1 = ‘)’; // Unicode value 41
byte v2 = 13;
printIntToStr(“v1:”, v1); // 41
printIntToStr(“v2:”, v2); // 13
printIntToStr(“~v1:”, ~v1); // -42
printIntToStr(“v1 & v2:”, v1 & v2); // 9
printIntToStr(“v1 | v2:”, v1 | v2); // 45
printIntToStr(“v1 ^ v2:”, v1 ^ v2); // 36
}
public static void printIntToStr(String label, int result) {
System.out.println(label);
System.out.println(” Binary: ” + Integer.toBinaryString(result));
System.out.println(” Hex: ” + Integer.toHexString(result));
System.out.println(” Decimal: ” + result);
}
}
Output from the program:
Click here to view code image v1:
Binary: 101001
Hex: 29
Decimal: 41
v2:
Binary: 1101
Hex: d
Decimal: 13
~v1:
Binary: 11111111111111111111111111010110
Hex: ffffffd6
Decimal: -42
v1 & v2:
Binary: 1001
Hex: 9
Decimal: 9
v1 | v2:
Binary: 101101
Hex: 2d
Decimal: 45
v1 ^ v2:
Binary: 100100
Hex: 24
Decimal: 36