Python 3, Converting a string storing binary data to Int

与世无争的帅哥 提交于 2021-02-05 02:17:51

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/18311500/python-3-converting-a-string-storing-binary-data-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!