+ 2

Binary number to decimal number

I have seen a code, which I am unable to understand the logic. Anyone please help! This is the code: d=0 for s in "00010000": d = d*2 + int(s) print(d)

24th Jan 2020, 3:55 AM
Prithvi
6 Respostas
+ 4
Prithvi This is an example of 'Explicit is better than implicit' The code you showed is clever, but not easilly understood by humans Normally you start at the position of the Least Significant Bit, wich is on the right. You then multiply the value with the base to the power of the position and move through from right to left and add all together. The position of the bit is explicitly named By starting on the left you get the same effect but the position is not explicitly named. For 010000 from right to left you have a 1 at position 4. So 1 x 2^4 and by following your prog you get. (0+1) x 2 x 2 x 2 x 2 which is equal to 1 x 2^4 So it is more difficult for a user to understand what is happening.
24th Jan 2020, 9:36 AM
Louis
Louis - avatar
+ 7
Nope... from the right side and it is a bit tricky. Do it in decimal with 321 D=0 D = 0×10 +3 =3 D = 3×10+2 =32 D= 32×10 + 1= 321 Check that the digit at 3rd place from right is multiplied 3 times by 10 And so on.
24th Jan 2020, 6:23 AM
Oma Falk
Oma Falk - avatar
+ 6
Ha, nice concise way to do that. :) I have found this article which explains the logic of binary system and how you convert it. After you've read it, this loop should have become understandable. https://www.electronics-tutorials.ws/binary/bin_2.html
24th Jan 2020, 4:33 AM
HonFu
HonFu - avatar
+ 1
Thank you for your time. I understand the concept of conversion, but I am not understanding the logic of the code. Does that code take s in "00010000" from last digit automatically. And if so, what is "int(s)" and assumed that d=0 initially.
24th Jan 2020, 5:24 AM
Prithvi
+ 1
Louis Thank you. You have explained a lot, I am still not understanding. I know I have asked a lot, but why is it (0+1)×2×2×2×2? If I had understood this correctly, d=2 by default until the bit reaches '1' and keep on adding the result.
24th Jan 2020, 12:38 PM
Prithvi
+ 1
Prithvi Study this code and see if you can figure it out. https://code.sololearn.com/cFCmlVrHpC4J/?ref=app
25th Jan 2020, 7:55 AM
Louis
Louis - avatar