Python 3 Converting a String Storing Binary Data to Int

I have a Number variable that is "0b11001010", and I want it to be of type int, like a regular binary file, like 0b11001010

Number = "0b11001010" NewNumber = 0b11001010 

Is there a really easy way and I don’t notice it?

Thanks.

+4
source share
1 answer

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

 >>> 0b11001010 202 

The same thing will happen with octal and hexadecimal values. This way you can convert the binary string to an integer with the int() function base argument, for example:

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

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

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

 >>> bin(202) 0b11001010 
+9
source

Source: https://habr.com/ru/post/1497771/


All Articles