1

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.

Nat Riddle
  • 928
  • 1
  • 10
  • 24
LLocas
  • 29
  • 1
  • 1
  • 4

3 Answers3

7

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}.

Marko Borković
  • 1,884
  • 1
  • 7
  • 22
  • 03b cannot be automatic, when I put a byte I don't want to change to 08b – LLocas Aug 10 '21 at 13:12
  • 1
    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. – Marko Borković Aug 10 '21 at 13:15
2

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
Red
  • 26,798
  • 7
  • 36
  • 58
0

Python 2 & 3

number = 128

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

Python 3

f"{number:b}"
Antonio
  • 304
  • 2
  • 11