Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the 0b in binary

I am trying to convert a binary number I have to take out the 0b string out.

I understand how to get a bin number

x = 17

print(bin(17))

'0b10001'

but I want to take the 0b in the string out and I am having some issues with doing this. This is going to be within a function returning a binary number without the 0b.

like image 728
VChocolate Avatar asked May 22 '16 18:05

VChocolate


5 Answers

Use slice operation to remove the first two characters.

In [1]: x = 17

In [2]: y = bin(x)[2:]

In [3]: y
Out[3]: '10001'
like image 143
Vedang Mehta Avatar answered Oct 16 '22 13:10

Vedang Mehta


use python string slice operation.

a = bin(17)
b = bin(17)[2:]

to format this to 8-bits use zfill.

c = b.zfill(8) 
like image 26
Tanu Avatar answered Oct 16 '22 11:10

Tanu


It's easy just make this function:

def f(n):print('{:0b}'.format(n))
f(17)
>>> 10001
like image 24
just 4 help Avatar answered Oct 16 '22 12:10

just 4 help


format(17, 'b')
>>> '10001'

Use the format() builtin. It also works for hexadecimal, simply replace 'b' with 'x'.

https://docs.python.org/3/library/functions.html#format

like image 3
NuclearPeon Avatar answered Oct 16 '22 11:10

NuclearPeon


with Python 3.6 you can use f-strings

print( f'{x:b}' )
'10001'
like image 2
Diego Roccia Avatar answered Oct 16 '22 11:10

Diego Roccia