6

I already tried converting it to a string, adding 0 to it, but it still only shows me the decimal value, how can I make it show me its binary value?

If I try this:

binary = 0b010
print(binary)

or this:

binary = 0b010
print(str(binary))

which outputs this:

2

I also tried this:

binary = 0b010
print("{0:b}".format(binary))

which outputs this:

10

Desired output:

010

The bad part is that it does not fill in the number of 0 on the left, it gives me an output of 10 when I want 010, but I want it to show the number of 0 possible for any binary that I put.

I'm new to Python, but every time I look for how to do it, it only appears to me as converting from integer to binary and showing it. But I can't use the bin() function, so I resorted to asking it here directly, thanks for your understanding.

10
  • Does this answer your question? Python int to binary string? Commented Aug 10, 2021 at 12:48
  • @WArnold I Clarify that I cannot use the bin function Commented Aug 10, 2021 at 12:48
  • You can use format: print("0b{:b}".format(number)). Commented Aug 10, 2021 at 12:48
  • It is basically, binary[2:] Commented Aug 10, 2021 at 12:49
  • 1
    That is because binary is an int. There is no difference in typing binary = 2 and binary = 0b010 Commented Aug 10, 2021 at 12:58

3 Answers 3

9

You have a couple of ways of going about it.

The one that fits your use case the best is the format() method:

binary = 0b010

print("{:03b}".format(binary))

Which outputs:

010

Changing the 3 in {:03b} will change the minimum length of the output(it will add leading zeros if needed).

If you want to use it without leading zeros you can simply do {:b}.

Sign up to request clarification or add additional context in comments.

2 Comments

03b cannot be automatic, when I put a byte I don't want to change to 08b
It is impossible for it to be automatic because the variable itself doesn't know how many zeros you put when declaring it. Again 0b00000010, 0b010 and 2 are exactly the same in the pythons eyes.
4

You can try defining your own function to convert integers to binary:

def my_bin(x):
    bit = ''
    while x:
        bit += str(x % 2)
        x >>= 1
    return '0' + bit[::-1]

binary = 0b010
print(my_bin(binary))

Output:

010

Comments

2

Python 2 & 3

number = 128

bin(number)
format(number, 'b')
"{0} in binary {0:b}".format(number)

Python 3

f"{number:b}"

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.