# Bitwise

### Bitwise essentials

- bitwise perform operations on individual bits of values
- used for testing and setting of individual bit flags in values
- if any of arguments is long, the result is long
- otherwise, the result is int

### Bitwise complement (NOT) (~)

What is it: operator

Type: unary

Looks like: ~

A.k.a. bitwise complement, NOT

Numbers of operands: 1

Action: inverts each byte of operand, converts 1 to 0 and *vice versa*

Name in logic: negation

```
byte b = ~15
~00001111
_________
11110000
result in 2's complement decimal: -16
```

Bitwise complement can be executed on flags (to be continued).

### Bitwise AND (&)

What is it: operator

Type: binary

Looks like: &

A.k.a. AND

Numbers of operands: 2

Action: boolean AND operation on individual bits of both operands - if a bit is set (positive, 1) in both operands, the result also has the bit set; otherwise it is 0

Name in logic: conjunction

```
binary:
00001010 & 00000111 = 00000010
decimal:
11 & 6 = 2
00001011 &
00000110
________
00000010
```

### Bitwise OR (|)

What is it: operator

Type: binary

Looks like: ( | ) |

A.k.a. OR

Numbers of operands: 2

Action: boolean OR operation on individual bits of both operands - if a bit is set (positive, 1) in at least one operand, the result is also positive.

Name in logic: alternative

```
binary:
00001010 | 00000111 = 00001111
decimal:
11 | 6 = 15
00001011 |
00000110
________
00001111
```

### Bitwise XOR (^)

What is it: operator

Type: binary

Looks like: ^

A.k.a. XOR

Numbers of operands: 2

Action: boolean XOR operation on individual bits of both operands. The result is positive (bit is set, 1) if corresponding bits in both operands are different.

Name in logic: exclusive alternative

```
binary:
00001010 ^ 00000111 = 00001101
decimal:
11 ^ 6 = 13
00001011 ^
00000110
________
00001101
```