简体   繁体   中英

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 eg 0b11001010

Number = "0b11001010"
NewNumber = 0b11001010

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

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM