This will cover bitwise operations and examples of their usages in C. These operations are extremely fast as CPUs are built with processors meant to do these operations directly without having to calculate multiple conditionals for each bit. A 64-bit processor can do these operations on a 64-bit number in a single operation, likewise a 32-bit processor can do these operations on a 32-bit number with a single operation.
Operator | Symbol |
---|---|
AND | & |
OR | | |
NOT | |
XOR | |
Left Shift | << |
Right Shift | >> |
Operator: Ampersand (&
)
Syntax: ``
Takes two inputs applying the Logical AND to each pair of corresponding bits in the input.
int a = 7; //0111
int b = 9; //1001
int aANDb = a & b; //0001 or 1
Operator: Pipe (|
)
Syntax:
Takes two inputs applying the Logical OR to each pair of corresponding bits in the input.
int a = 7; //0111
int b = 9; //1001
int aORb = a | b; //1111 or 15
Operator: Tilde (~
)
Syntax: ~value
Simply applies the Logical NOT to each bit in the input. This operation takes only a single input making it a Unary Operation.
int a = 7; //0111
int b = ~A; //1000 or 8
Operator: Caret (^
)
Syntax: val1 ^ val2
Takes two inputs applying the Logical XOR to each pair of corresponding bits in the input.
int a = 7; //0111
int b = 9; //1001
int aXORb = a ^ b; //1110 or 14
Bitshift operations move all the bits in a number left or right by a certain amount. They only work on integers, and the value of amount
should always be positive.
Operator: <<
Syntax: value << amount
Functionality:
amount
.amount
.int a = 10; //00001010
int amount = 2;
int shifted = a << amount; //00101000 or 40
Operator: >>
Syntax: value >> amount
Functionality:
amount
.amount
(performs an integer division, discarding any remainder).int a = 40; //00101000
int amount = 2;
int shifted = a >> amount; //00001010 or 10