I am working on a simple conversion project for practice that converts numbers to and from binary and hex. But as I was writing the code I ran into an error when working on the hex function.
numArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F']
valArr = []
print('Please input number to convert here... ')
userIn = int(input('>>> '))
userData = userIn
breakDown = True
while breakDown:
leftOver = userData / 16
leftConv = int(leftOver)
remainder = userData % 16
userData = leftConv
valArr.append(remainder)
print(valArr)
if leftConv < 1:
valArr.reverse() #result I want converted in this order
print(valArr) # Prints to console the above
break
for x in range(0, len(numArr)):
numArrVals = numArr[x]
for y in range(0, len(valArr)):
valArrVals = valArr[y]
if valArrVals == x:
print(numArrVals) # Prints out of order, lowest to highest
The output of this code, when entering lets say... 999 is 37E. This is because the if statement in the 'y' for loop is printing from lowest to highest values. The real value of 999 in hex is 3E7.
TL:DR - Is there a way to compare two differently sized arrays in their order of index rather than size of number? I'm sure the solution is easy, and I'll probably end up figuring it out later after this is posted. Any help till then is greatly appreciated though? Maybe a python dictionary is the way to go?
I don't quite understand what you are trying to do with the two nested for
loops at the end (I can imagine it roughly, but trying to explain what is wrong is more difficult than just showing how to do it correctly).
Essentially you already have your result in valArr
after reversing it. You just need to convert each number x
to the corresponding hexadecimal digit, which conveniently is numArr[x]
.
So instead of
for x in range(0, len(numArr)): numArrVals = numArr[x] for y in range(0, len(valArr)): valArrVals = valArr[y] if valArrVals == x: print(numArrVals) # Prints out of order, lowest to highest
you can just use
for x in valArr:
print(numArr[x])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.