Home > OS >  How to convert a string "0bxxxx" to a binary?
How to convert a string "0bxxxx" to a binary?

Time:06-07

Consider the following variables as an example :

x = "0b1"
y = 0b1

I am looking for a way to convert x to y, and vice-versa.

Edit : I add that I read x from a file, and I am not supposed to know something more than x can be any binary 0b1, 0b10 ...

I would really appreciate an answer with an explanation. Thanks.

CodePudding user response:

Python doesn't have a separate type for binary numbers when you type 0b1 there it just gets interpreted as base 2 and is still stored as a base 10 integer at the end so for converting from a string '0b1' you can just convert it to int while telling it that the value is in base 2

y = '0b1'
print(int(y, 2))

the bin function also just gives you a binary representation of the integer as a string

CodePudding user response:

You can try something like this : -

x = "0b1"
y = 0b1

#type of x and y before change
print(type(x))
print(type(y))


x,y=y,x
print(bin(x))
print(y)

#type of x and y after change
print(type(x))
print(type(y))
  • Related