-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q10.py
130 lines (90 loc) · 2.02 KB
/
Q10.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""
Aledutron
SPPU 2019 FE PPS Lab
SPPU First Year (FE) Programming and Problem Solving (PPS) Lab Assignments (2019 Pattern)
Youtube PPS Playlist Link: https://youtube.com/playlist?list=PLlShVH4JA0osTzddxh-2s1yaigpyp6DRx&si=5RWSN_MmtX1FACb1
Problem Statement:
Q10
To input binary number from user and convert it into decimal number.
Explaination Video Link: https://www.youtube.com/watch?v=yRnb482gdiI&list=PLlShVH4JA0osTzddxh-2s1yaigpyp6DRx&index=11&pp=iAQB
"""
# decimal base - 10
# 00
# 01
# 02
# 03
# 04
# 05
# 06
# 07
# 08
# 09
# 10
# 11
# 12
# 13
# 14
# 19
# 20
# 21
# 22
# 23
# 29
# 30
# ....
# binary base - 2
# 0 # -> 0V -> off 0
# 1 # -> 5V -> on 1
# 10 2
# 11 3
# 100 4
# 101 5
# 110 6
# 111 7
# 1000 8
# 1001 9
# 1010 10
# 1011 11
# 3210 - base -> 2
# 0000
# 0001
# 0010
# 0011
# 0100
# 0101
# 0110
# 0111
# 1000
# 1001
# 1010
# 1011
# summation cv * 2 ^ cn
# 0 * 2 ^ 3(8) + 0 * 2 ^ 2(4) + 0 * 2 ^ 1(2) + 0 * 2 ^ 0(1)
# 0 + 0 + 0 + 0 = 0 -> decimal
# 0 * 2 ^ 3(8) + 0 * 2 ^ 2(4) + 0 * 2 ^ 1(2) + 1 * 2 ^ 0(1)
# 0 + 0 + 0 + 1 = 1 -> decimal
# 0 * 2 ^ 3(8) + 0 * 2 ^ 2(4) + 1 * 2 ^ 1(2) + 0 * 2 ^ 0(1)
# 0 + 0 + 2 + 0 = > 2 _ > decimal
# 0 * 2 ^ 3(8) + 0 * 2 ^ 2(4) + 1 * 2 ^ 1(2) + 1 * 2 ^ 0(1)
# 0 + 0 + 2 + 1 = > 3 -> decimal
# 0 * 2 ^ 3(8) + 1 * 2 ^ 2(4) + 0 * 2 ^ 1(2) + 0 * 2 ^ 0(1)
# 0 + 4 + 0 + 0 = > 4
# 0 * 2 ^ 3(8) + 1 * 2 ^ 2(4) + 0 * 2 ^ 1(2) + 1 * 2 ^ 0(1)
# 0 + 4 + 0 + 1 = > 5
# left -> least significant bit
# right -> more significant bit
# summation of columnval * 2 ^ columnnum
def binarytodecimal(binaryval):
decimalnum = 0
for columnnum in range(len(binaryval)):
columnnum = int(columnnum)
columnval = int(binaryval[-(columnnum+1)])
# print(f"{columnval} * 2^{columnnum}")
decimalnum += (columnval * (2 ** columnnum))
return decimalnum
# 0101 -> 4 -> 0123
# binarynumfromuser = input("Enter binary number: ")
# print(binarytodecimal(binarynumfromuser))
# print(int(binarynumfromuser, 2))
print(bin(5458)[2:] == "1010101010010")
# 1010101010010