简体   繁体   English

如何将二进制数的字符串转换为二进制数?

[英]How to convert a string of a binary number into a binary number?

x = '0b001'

I need x to be 0b001 so that is a binary number, I tried doing int('0b001') however the 'b' gives an error due to being a character.我需要x0b001所以这是一个二进制数,我尝试做int('0b001')但是由于是一个字符,'b' 给出了一个错误。

How to convert '0b001' into a binary?如何将'0b001'转换成二进制?

If you want to get a decimal value of binary string, you can use int() with base argument set to 2 .如果要获取二进制字符串的十进制值,可以使用int()并将base参数设置为2

x = '0b001'
decimal_x = int(x, 2)
decimal_x = 1

If you want to remove the '0b' from the binary string, do a string slice as below如果要从二进制字符串中删除“0b”,请执行如下字符串切片

x = '0b001'
x = x[2:]
x = '001'

Try specifying the base number to 0 :尝试将基数指定为0

>>> int('0b001', 0)
1
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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