O
O
old_stalin2021-09-02 21:29:57
Python
old_stalin, 2021-09-02 21:29:57

How to convert from decimal to binary with a certain number of characters?

I know that there is a bin() function, is it possible to somehow specify the number of characters, let's say bin(3) will make 11, but I need 0011, can there be any analogue?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Antonio Solo, 2021-09-03
@old_stalin

zfill will save a young programmer

>>> bin(777)[2:].zfill(22)
'0000000000001100001001'

although I would just use format
>>> format(777, '022b')
'0000000000001100001001'

V
Vindicar, 2021-09-02
@Vindicar

Format the resulting string .

s1 = bin(3) #0b11
s2 = s1[2:] #11
s3 = '{0:>04s}'.format(s2) #0011
print(s3)
# ну или в одну строку
print('{0:>04s}'.format(bin(3)[2:]))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question