-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathbit_manipulation.py
54 lines (38 loc) · 980 Bytes
/
bit_manipulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word.
#
# common bit-wise operation
#
# operations priority:
# {}[]() -> ** -> ~ -> -x -> *,/,% -> +,- -> <<,>> -> & -> ^ -> | -> <>!= -> is -> in -> not x -> and -> or
def bit_wise_operations(a, b):
# not
~a
# or
a | b
# and
a & b
# xor
a ^ b
# shift operators
a << b
a >> b
# subtraction
a & ~b
# set bit, assign to 1
a |= 1 << b
# clear bit, assign to 0
a &= ~(1 << b)
# test bit
if a & 1 << b: pass
# extract last bit
a & -a
# remove last bit
a & (a - 1)
# check is odd or even
if a & 1: print('odd')
# clear right n bit
a & (~0 << b)
# clear left until to n
a & ((1 << b) - 1)
# reference
# https://leetcode.com/problems/sum-of-two-integers/discuss/84278/A-summary%3A-how-to-use-bit-manipulation-to-solve-problems-easily-and-efficiently