FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/bit/bit_operation.py at master · ivan1911/algorithms-python · GitHub
ivan1911
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
bit
/
bit_operation.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
37 lines (33 loc) · 1.04 KB
Breadcrumbs
algorithms-python
/
algorithms
/
bit
/
bit_operation.py
Copy path
File metadata and controls
37 lines (33 loc) · 1.04 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Fundamental bit operation:
get_bit(num, i): get an exact bit at specific index
set_bit(num, i): set a bit at specific index
clear_bit(num, i): clear a bit at specific index
update_bit(num, i, bit): update a bit at specific index
"""
"""
This function shifts 1 over by i bits, creating a value being like 0001000. By
performing an AND with num, we clear all bits other than the bit at bit i.
Finally we compare that to 0
"""
def
get_bit
(
num
,
i
):
return
(
num
&
(
1
<<
i
))
!=
0
"""
This function shifts 1 over by i bits, creating a value being like 0001000. By
performing an OR with num, only value at bit i will change.
"""
def
set_bit
(
num
,
i
):
return
num
|
(
1
<<
i
)
"""
This method operates in almost the reverse of set_bit
"""
def
clear_bit
(
num
,
i
):
mask
=
~
(
1
<<
i
)
return
num
&
mask
"""
To set the ith bit to value, we first clear the bit at position i by using a
mask. Then, we shift the intended value. Finally we OR these two numbers
"""
def
update_bit
(
num
,
i
,
bit
):
mask
=
~
(
1
<<
i
)
return
(
num
&
mask
)
|
(
bit
<<
i
)
Back
|
FazBrowse Home
|
New Git URL