Bitwise Complement Operator


Syntax

 ~prefix_expression

Notes

Prefix operators group right to left.

The truth table for bitwise complement is depicted below.

P ~P
0 1
1 0

The bitwise complement operator applies the above truth table to successive bits in an integer as shown below.

Hex f f 0 0
binary 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0

~

Hex 0 0 f f
binary 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

Examples

The bitwise complement operator can be combined with the bitwise and operator to clear an individual bit as follows.

enum file_flags {not_open       = 0x0
                 open_for_read  = 0x1
                 open_for_write = 0x2
                 random         = 0x4
                 sequential     = 0x8}
 
flags = file_flags.open_for_read | file_flags.open_for_write  // Set open for read and write.
flags = flags & ~file_flags.open_for_write                    // Clear open for write.

The above logic first sets flags to be open for read and open for write via the bitwise or operator. The next statement clears the flag open_for_write using the bitwise complement and the bitwise and operators. The bitwise operations are shown below (low order byte only):


Hex 0 1
Binary 0 0 0 0 0 0 0 1

|

Hex 0 2
Binary 0 0 0 0 0 0 1 0

gives

Hex 0 3
Binary 0 0 0 0 0 0 1 1

&

Hex f d
Binary 1 1 1 1 1 1 0 1

gives

Hex 0 1
Binary 0 0 0 0 0 0 0 1