FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pygorithm/pygorithm/binary/base10.py at master · lambdafunc/pygorithm · GitHub
lambdafunc
/
pygorithm
Public
forked from
OmkarPathak/pygorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pygorithm
/
pygorithm
/
binary
/
base10.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
72 lines (58 loc) · 1.65 KB
Breadcrumbs
pygorithm
/
pygorithm
/
binary
/
base10.py
Copy path
File metadata and controls
72 lines (58 loc) · 1.65 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Binary: Base10
Conversions from base10 to:
- base2
- base16
Author: Ian Doarn
"""
HEX_VALUES
=
{
0
:
'0'
,
1
:
'1'
,
2
:
'2'
,
3
:
'3'
,
4
:
'4'
,
5
:
'5'
,
6
:
'6'
,
7
:
'7'
,
8
:
'8'
,
9
:
'9'
,
10
:
'A'
,
11
:
'B'
,
12
:
'C'
,
13
:
'D'
,
14
:
'E'
,
15
:
'F'
}
def
to_base2
(
n
,
visualize
=
False
):
"""
Divide each number by 2 using
the % operator.
Reverse the resulting list of numbers
and return the result
:param n: decimal number
:param visualize: Show process
:return: binary number
"""
_list
=
[]
while
n
>
0.5
:
if
visualize
:
print
(
"{} / 2 = {} || {} % 2 = {}"
.
format
(
str
(
n
),
str
(
n
/
2
),
str
(
n
),
str
(
n
%
2
)))
_list
.
append
(
n
%
2
)
n
=
int
(
n
/
2
)
# Reverse the list, turn each number to a string,
# join the string, and convert it back to an integer
return
int
(
''
.
join
([
str
(
i
)
for
i
in
_list
[::
-
1
]]))
def
to_base16
(
n
,
visualize
=
False
):
"""
Convert decimal number to hexadecimal
Divide the number by 16 and add the remainder
to a list, round down the value after division
and repeat till our value is 0
Reverse the results list, get each values respective
hex value using HEX_VALUES map
:param n: decimal number
:param visualize: Show process
:return: hexadecimal number
"""
_list
=
[]
while
n
!=
0
:
if
visualize
:
print
(
"{} % 16 = {} -> hex = {}"
.
format
(
str
(
n
),
str
(
n
%
16
),
HEX_VALUES
[
n
%
16
]
))
_list
.
append
(
HEX_VALUES
[
n
%
16
])
n
=
int
(
n
/
16
)
if
visualize
:
print
(
_list
)
print
(
"reversed = "
+
str
(
_list
[::
-
1
]))
return
''
.
join
(
_list
[::
-
1
])
Back
|
FazBrowse Home
|
New Git URL