I am trying to build a standard function to convert any decimal value to its octal, hexadecimal and binary equivalent but it doesn't work for binary for some reason. I tried putting extra precautions into the conditional statement to check for base 2 but it still did not work.
This is the function (I know that this doesn't work well with hexadecimal values. I am going to take care of that afterwards):
def convert(num, base):
remainder = num % base
conv = []
if(remainder == 0):
conv.append('0')
elif(remainder != 0 and base == 2):
conv.append('1')
else:
conv.append(str(remainder))
result = ''.join(conv)
output = result[::-1]
return int(output)
In the line elif(remainder != 0 and base == 2):
, I am checking if the remainder isn't 0 and the base is 2 to add a 1 into the temporary conv
list. I am then converting the list to a string, reversing it and returning it as an int.
For example. If the input is 17
, the output needs to be this:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001
These are the functions that take care of the input and the printing:
def print_formatted(number):
# your code goes here
for i in range(number):
print(
str(i + 1) + " " +
str(convert(i + 1, 8)) + " " +
str(convert(i + 1, 16)) + " " +
str((convert(i + 1, 2)))
)
if __name__ == '__main__':
n = int(input())
print_formatted(n)
Update
Instead of going through the entire equation, I decided to go with the built-in functions and trim the first two characters (i.e 0b
) so it fits the format well. I am trying to space them away from each other based on the width of the binary output but I couldn't figure out a way of doing that. This is what I have so far:
def convert(num, base):
# get the highest power
val = ''
hex_char_list = ['A', 'B', 'C', 'D', 'E', 'F']
if(base == 2):
bin_num = bin(num)
bin_list = list(bin_num)
bin_list_2 = bin_list[2:]
val = ''.join(bin_list_2)
if(base == 8):
oct_num = oct(num)
oct_list = list(oct_num)
oct_list_2 = oct_list[2:]
val = ''.join(oct_list_2)
if(base == 16):
hex_num = hex(num)
hex_list = list(hex_num)
hex_list_2 = hex_list[2:]
val = ''.join(hex_list_2)
if val in hex_char_list:
val = val.upper()
return val
def print_formatted(number):
# your code goes here
width = len(convert(number, 2).format(number))
for i in range(number):
print(
str(i + 1) + width +
str(convert(i + 1, 8)) + width +
str(convert(i + 1, 16)) + width +
str((convert(i + 1, 2)))
)
if __name__ == '__main__':
n = int(input())
print_formatted(n)