Bitwise Operators

Run Settings
LanguagePython
Language Version
Run Command
''' Bitwise operators look at a type (or set of types) in their binary representation and operate on those representations. 1. Binary Comparisons ----- There are three operators used in binary comparisons: | - or & - and ^ - exclusive or (one or the other, but not both) The behavior of these operators is fairly simple, as they run binary comparisons in O(n) time. The following examples show how each operator treats its operands in a comparison. As is typical in comparisons, 1 represents "true" and 0 represents "false". 7 = 111 3 = 011 7 | 3 --> 1 1 1 0 1 1 ----- 1 1 1 = 7 7 & 3 --> 1 1 1 0 1 1 ----- 0 1 1 = 3 7 ^ 3 --> 1 1 1 0 1 1 ----- 1 0 0 = 4 2. Binary Shifts ----- Binary shifts simply move a binary representation b n digits to the right or left. b << n shifts to the left; b >> n shifts to the right 7 = 111 7 << 1 = 1110 = 8 + 4 + 2 + 0 = 14 7 >> 1 = 011 = 0 + 2 + 1 = 3 3. Binary Negation ----- Binary negation transforms a binary representation into its complement. This operation uses the ~ operator to negate a data type. 7 = 0111 ~7 --> 0 1 1 1 + 0 ----------- 1 0 0 0 + 1 = -8 The negation of 7 is -8; this happens because the bit that denotes the sign is also complemented; positive numbers have a signage bit of 0, and negative numbers have a signage bit of 1. ''' print("7 | 3 =", 7 | 3) print("7 & 3 =", 7 & 3) print("7 ^ 3 =", 7 ^ 3) print("\n7 << 1", 7 << 1) print("7 >> 1", 7 >> 1) print("\n~7 =", ~7)
Editor Settings
Theme
Key bindings
Full width
Lines