Binary to decimal | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Binary to decimal

i want to convert a binary number to decimal. Let's say I've got a=00000110 int(a, 2) doesn't work (tells me "int() can't convert non-string with explicit base") Is there a specific syntax that I should be aware of ? Can't I put a variable in here ? Thanks in advance !

13th Oct 2017, 3:48 PM
Bilal Naeem
Bilal Naeem - avatar
3 Answers
+ 4
As written, this reports "Invalid Token" (a syntax error): a=00000110 If you were going to use it that way, Python expects numbers starting with 0 to be followed by a symbol indicating what type of number it is (here, '0b' means binary): a=0b00000110 Now ignoring 0b..., to resolve the second error (...a non-string...), it's really just saying "send me a string".
13th Oct 2017, 4:20 PM
Kirk Schafer
Kirk Schafer - avatar
+ 3
int(str(a),2)
13th Oct 2017, 4:15 PM
Dark0d3
Dark0d3 - avatar
+ 2
If you take into account what @Kirk has stated and write your binary number as a=0b00000110 all you need to do to convert to the string '6' is str(a) then you can convert that back into an integer by using int() I.E. int(str(a)). If you are using a string representation of the binary number like a='00000110' (with or without the 0b prefix) then you can do int(a, 2) to get the decimal value.
13th Oct 2017, 6:35 PM
ChaoticDawg
ChaoticDawg - avatar