+ 5

How does this code snippet work?

I came across this snippet recently which turns a binary number into a decimal number, but I don't understand how it happens. print(int('101010',2)) # output 42

23rd May 2020, 10:01 AM
Rik Wittkopp
Rik Wittkopp - avatar
6 Respostas
+ 4
Syntax: the 2. argument in int is the base of the numbers which converts the string of that number base to an integer. Binary numbers: From left to right multiply 2^(index) with the current value. In this case: 1* 2^5 + 0* 2^4 + 1*2^3 + 0 *2^2 + 1* 2^1 + 0*2^0 = 32+8+2=42
23rd May 2020, 10:11 AM
Jnn
Jnn - avatar
+ 3
Jnn Wow 🤯 Your explanation has made me realise that I don't understand binary as well as I thought. Thanks heaps
23rd May 2020, 10:37 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Do you not understand how binary numbers work or why the syntax is that way?
23rd May 2020, 10:04 AM
Jnn
Jnn - avatar
+ 2
Code Crasher Thanks buddy. I am learning heaps tonight. Still haven't understood everything, but getting closer
23rd May 2020, 11:47 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Code Crasher Thanks. I am working on a code to re-enforce this concept in my mind. Appreciate the time you have taken to help
23rd May 2020, 12:25 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Jnn I don't understand the syntax of the code. How does it interprete the code to create the output?
23rd May 2020, 10:09 AM
Rik Wittkopp
Rik Wittkopp - avatar