A Phototactic Coder
A Phototactic Coder

Reputation: 343

Binary to Decimal (mathematics way)

If there is an binary number:10011100 It is 156 in decimal.

I want to use mathematics way to make binary to decimal.

For example: binary: 10011100

the first number is 1: 2**7
the forth number is 1: 2**4
the fifth number is 1: 2**3
the sixth number is 1: 2**2

then 2**7+2**4+2**3+2**2 = 156

I think, I need to use string.find() method.

>>> my_str = '10011100'   
>>> my_str = my_str[::-1]   
>>> print(my_str)   
00111001   
>>> my_str.find('1')   
2   
>>>  

I just can find the first '1'.

How to find all the index of '1'?

Upvotes: 1

Views: 278

Answers (3)

I_M
I_M

Reputation: 1

Binary Number: If you are considering why binary number has a base 2 always well the answer is a binary number is expressed in the base-2 because it uses only two symbols: typically "0" (zero) and "1" (one). eg 10011100 (only "zero" and "one" used)


If there is an binary number:10011100 It is 156 in decimal. The Binary number here is 10011100 it always has a base 2 even if it is not written 10011100 is same as 10011100 base 2

Convert Binary to Decimal

  • We start from the most right number and move toward left

    • Multi the binary number with 2 that is the base and the power(^) keeps increasing by 1

      (0*2^0)+(0*2^1)+(1*2^2)+(1*2^3)+(1*2^4)+(0*2^5)+(0*2^6)+(1*2^7)

      =156


If you want to under stand more clearly here is a link [https://www.mathwarehouse.com/non-decimal-bases/convert-binary-to-decimal.php?ref=driverlayer.com][1]

Upvotes: 0

root
root

Reputation: 80346

You may also check the built-in int() function that takes a base argument:

int(x[, base]) -> integer

In [1]: my_str = '10011100'

In [2]: int(my_str,2)
Out[2]: 156

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318508

Why do you want to retrieve the indexes? You can simply iterate over the bits like this:

num = sum(2**i for i, bit in enumerate(my_str) if bit == '1')

Anyway, you can get the indexes like this if you prefer two separate steps:

indexes = [i for i, bit in enumerate(my_str) if bit == '1']
num = sum(2**i for i in indexes)

Upvotes: 7

Related Questions