Binary Logic Bit Operations in C and C++: Programming Practice
Binary Logic Bit Operations in C and C++: Programming Practice
Programming Practice
Common Synonyms for True and False
0 false off unset zero
1 true on set non-zero
C Bitwise Operators
& binary bitwise AND
^ binary bitwise exclusive OR (XOR)
| binary bitwise inclusive OR
~ unary bitwise complement (NOT)
Toggling means that if the bit is 1, it is set to 0, and if the bit is 0, it is set to 1.
OR truth table
0 | 0 = 0
1 | 0 = 1
0 | 1 = 1
1 | 1 = 1
Operator/
Languages/ Returned Value Example Example Result
Operation
Two-place operator,
& 0000 1100
return a word with each x = 12;
& 0000 1010
bit set only if the y = 10;
---------
C, C++, Java
corresponding bit is set z = x & y; // z is 8 0000 1000 = 8 (decimal)
Bitwise And
in both operands.
Two-place operator,
|
return a word with each 0000 1100
x = 12;
C, C++, Java bit set if either or both y = 10;
| 0000 1010
---------
Bitwise Or of the the corresponding z = x | y; // z is 14
0000 1110 = 14 (decimal)
bits are set in the
operands.
Two-place operator,
return a word with each
^
bit set only if the
0000 1100
C, C++, Java corresponding bit in one x = 12; ^ 0000 1010
Bitwise operand or the other but y = 10; ---------
z = x ^ y; // z is 6
Exclusive Or not both is set. This 0000 0110 = 6 (decimal)
operator can be thought
of as the bitwise not
equal to operator.
~ ~ 0000 1100
C, C++, Java Unary (one operand),
---------
Bitwise Not return a word with ones x = 12;
1111 0011 = -13
changed to zeros and z = ~ x // z is -13
(One's (8-bit two's
Complement) zeros to ones. complement decimal)
Two-place operator,
return a word with each 0000 1100
bit shifted toward the //
<< high end of the word by // shifted 3 places
C, C++, Java the specified number of x = 12;
z = x << 3; // z is 96
//
Left Shift vv
bits. ---------
x << y
0110 0000 = 96 (decimal
is equivalent to
x * 2y
RESET_CAR(fMercedes);
RESET_CAR(fCivic);
SET_LOCKED(fMercedes);
if( IS_LOCKED(fMercedes) != 0 )
{
UNSET_PARKED(fCivic);
}
TOGGLE_LOCKED(fMercedes);
return 0;
}