How does this code convert decimal to binary | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How does this code convert decimal to binary

#decimal to binary ''' This code is on python intermediate course: recursion practice's answer. The code is a easy to understand except in the return statement in which it became tricky. Can somebody explain to me in simple way. ''' def convert(num): if num == 0: return 0 else: return (num % 2 + 10 * convert(num // 2)) #explain this part decimal = int(input()) print(convert(decimal))

28th Apr 2022, 5:00 AM
Joseph Tiglao
Joseph Tiglao - avatar
2 Answers
+ 3
Continuation: Recursion in the code attempts to do exactly that. It keeps calling num%2 on the floor divided values for each iteration. You iterate this way until num//2 gives 0, in which case, it returns 0. One thing to notice is the multiplication by 10 (10 * convert(num // 2)). Even though we're writing out binary, we still need to follow the positions i.e ones place, tens place, hunderds place, etc. Ex: 321 = 3 * 100 + 2 * 10 + 1*1. So we multiply the result with a 10 for each iteration. This allows us to properly show the binary code. Hope this clarified the recursion part.
2nd May 2022, 10:00 PM
Pardha Saradhy
Pardha Saradhy - avatar
+ 1
Given a binary number, you can easily compute its decimal value by multiplying positions from right to left with increasing powers of 2. That is, 1st position from right is to be multiplied with 2**0, the next position with 2**1, the next with 2**2, so on.. A similar logic is being used to compute the binary value from its decimal value. The num%2 gives 1 if num is odd, gives 0 if num is even. This result is to be stored in the 1st position (right most). If it gave 1, we can subtract 1 from the number and proceed to the next step, which is a division by 2. This is precisely what floor division accomplishes. Ex: 7//2 gives 3, (7-1)/2 gives 3 too. If it gave 0 instead, we don't have to bother subtracting 1, which is also what floor division accomplishes. Next, we need to move to the 2nd position. The way to find 2nd position is to divide it by 2, as the second position has a factor of 2**1. Now we find if its even or odd again, by num%2, store the result in 2nd position.
2nd May 2022, 9:52 PM
Pardha Saradhy
Pardha Saradhy - avatar