Homework
Below is an example of decimal number to binary converter which you can use as a starting template.
def DecimalToBinary(num):
strs = ""
while num:
# if (num & 1) = 1
if (num & 1):
strs += "1"
# if (num & 1) = 0
else:
strs += "0"
# right shift by 1
num >>= 1
return strs
## making a function to convert a given character into it's ascii binary code, using the if conditional statement and ord() function
def CharToBinary(char):
return DecimalToBinary(ord(char)) if len(char) == 1 else False
def DecimalToOctal(num):
res = ""
digits = 7
while digits >= 0:
if (num - 8 ** digits) >= 0:
sub_res = 0
while (num - 8 ** digits) >= 0:
sub_res+=1
num -= 8 ** digits
res = res + str(sub_res)
else:
res = res + "0"
digits-=1
return res
def DecimalToHex(num):
hex_correlation = {
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"
}
res = ""
digits = 7
while digits >= 0:
if (num - 16 ** digits) >= 0:
sub_res = 0
while (num - 16 ** digits) >= 0:
sub_res+=1
num -= 16 ** digits
res = res + str(hex_correlation[sub_res])
else:
res = res + "0"
digits-=1
return res
# function to reverse the string
def reverse(strs):
print(strs[::-1])
# Driver Code
num = int(input("What is your desired number? "))
print("Binary of num {0} is: {1}".format(num, DecimalToBinary(num)))
char = input("What is your desired character? ")
print("Binary of character {0} is: {1}".format(char, CharToBinary(char)))
O_num = int(input("what is your desired number? "))
print("Octal representation of number {0} is: {1}".format(O_num, DecimalToOctal(O_num)))
H_num = int(input("what is your desired number? "))
print("Hexadecimal representation of number {0} is: {1}".format(H_num, DecimalToHex(H_num)))