Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base-2 binary number string to int

Tags:

python

I'd simply like to convert a base-2 binary number string into an int, something like this:

>>> '11111111'.fromBinaryToInt() 255 

Is there a way to do this in Python?

like image 660
Naftuli Kay Avatar asked Jan 19 '12 15:01

Naftuli Kay


People also ask

How do you convert binary to integer?

To convert binary integer to decimal, start from the left. Take your current total, multiply it by two and add the current digit. Continue until there are no more digits left. Here is an example of such conversion using the fraction 1011.

How do you convert binary to int in Python?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you convert a string to a binary number?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .


2 Answers

You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2) 255 

Here is documentation for Python 2, and for Python 3.

like image 114
unwind Avatar answered Oct 22 '22 23:10

unwind


Just type 0b11111111 in python interactive interface:

>>> 0b11111111     255 
like image 35
lengxuehx Avatar answered Oct 22 '22 22:10

lengxuehx