It's a lot easier if you thnk of hex as a integer (number).
There's a lot of tips on how to convert integers to different outcomes, but one useful string representation tool is .format()
which can format a integer (and others) to various outputs.
This is a combination of:
The solutions would be:
binary = '{:08b}'.format(int(hex_val, 16))
And the end result code would look something like this:
def toBin(hex_val):
return '{:08b}'.format(int(hex_val, 16)).zfill(8)
hexdec = input("Enter the hex number to binary ");
dynamic_array = [toBin(hexdec[idx:idx+2]) for idx in range(len(hexdec)) if idx%2 == 0]
print(dynamic_array[0] + " IAM" )
print(dynamic_array[1] + " NOA" )
print(dynamic_array[2] + " FCI" )
Rohit also proposed a pretty good solution, but I'd suggest you swap the contents of toBin()
with bin(int())
rather than doing it per print statement.
I also restructured the code a bit, because I saw no point in initializing dynamic_array
with a empty list. Python doesn't need you to set up variables before assigning values to them. There was also no point in creating strArray
just to replace the empty dynamic_array
with it, so concatenated three lines into one.
machnic also points out a good programming tip, the use of format()
on your entire string. Makes for a very readable code :)
Hope this helps and that my tips makes sense.