Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Choose number of bits to represent binary number

I am curious as to how I can change the number of bits to represent a binary number. For example, say I want express decimal 1 to binary. I use:

bin(1) and get 0b1.

How can I get the return to say 0b01 or 0b001 or 0b0001 etc?

like image 504
user1653402 Avatar asked Dec 03 '12 02:12

user1653402


2 Answers

Use the Format String Syntax:

>>> format(1, '#04b')
'0b01'
>>> format(1, '#05b')
'0b001'
>>> format(1, '#06b')
'0b0001'
like image 150
ekhumoro Avatar answered Sep 26 '22 12:09

ekhumoro


You can use str.zfill to pad the binary part:

def padded_bin(i, width):
    s = bin(i)
    return s[:2] + s[2:].zfill(width)
like image 24
Jesse the Game Avatar answered Sep 23 '22 12:09

Jesse the Game