Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3, Converting a string storing binary data to Int

I have the variable Number which is equal to "0b11001010" and I want it to be the type int like a normal binary is stored e.g. 0b11001010

Number = "0b11001010"
NewNumber = 0b11001010

is there a really simple way and I am overlooking it?

Thanks.

like image 365
James Clarke Avatar asked Aug 19 '13 10:08

James Clarke


People also ask

How do I convert a string to int in Python 3?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

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 I convert a string to an int?

Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int. If the string does not contain a valid integer then it will throw a NumberFormatException.

How do you convert string to binary in Python?

Method #1: The binary data is divided into sets of 7 bits because this set of binary as input, returns the corresponding decimal value which is ASCII code of the character of a string. This ASCII code is then converted to string using chr() function.


1 Answers

In python you can only create it as a binary value (as a syntactic sugar), it will be converted into an integer immediately. Try it for yourself:

>>> 0b11001010
202

The same thing will happen with octal and hexadecimal values. So you can convert your binary string to an integer, with the int() function's base argument like:

>>> int('0b11001010', 2)
202

After the conversion you can do any operations on it -- just like with an integer, since it is an integer.

Of course you can convert it back at any time to a binary string, with the builtin bin() function:

>>> bin(202)
0b11001010
like image 90
Peter Varo Avatar answered Sep 20 '22 15:09

Peter Varo