8

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?

3 Answers 3

13

Use the Format String Syntax:

>>> format(1, '#04b')
'0b01'
>>> format(1, '#05b')
'0b001'
>>> format(1, '#06b')
'0b0001'
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

0

I don't believe there's a builtin way to do this. However, since bin just returns a string, you could write a wrapper function which modifies the string to have the right number of bits:

def binbits(x, n):
    """Return binary representation of x with at least n bits"""
    bits = bin(x).split('b')[1]

    if len(bits) < n:
        return '0b' + '0' * (n - len(bits)) + bits
# 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.