Python 3,将存储二进制数据的字符串转换为Int [英] Python 3, Converting a string storing binary data to Int
问题描述
我有一个等于"0b11001010"的变量Number,我希望它是int类型,就像存储普通二进制文件一样.0b11001010
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?
谢谢.
推荐答案
在python中,您只能将其创建为二进制值(作为语法糖),它将立即转换为整数.自己尝试一下:
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
八进制和十六进制值也会发生相同的情况.因此,您可以使用 int()
函数的 base
参数将二进制字符串转换为整数,例如:
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.
当然,您可以随时使用内置的 bin()
函数将其转换回二进制字符串:
Of course you can convert it back at any time to a binary string, with the builtin bin()
function:
>>> bin(202)
0b11001010
这篇关于Python 3,将存储二进制数据的字符串转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!