Is there is any built in fn in python that converts decimal no. into equivalent binary with chosen no. of bits ( i.e i want to represent the no. 10 in the binary repersentation which is 1010 & i can choose no. of representing bits i.e 16 bits or whatever ?
-
Do you mean something like the `bin` function? – rlms Jan 25 '14 at 14:37
-
i do know about bin(n) but my question is how to represent it in my chosen no. of bits – Amr saad Jan 25 '14 at 14:42
-
What do you want to happen when you try and encode 256 in 8 bits? – rlms Jan 25 '14 at 14:55
2 Answers
"{0:016b}".format(10)
This will return the string 0000000000001010
.
The documentation is here: Format String Syntax
Here's the breakdown of the format string:
0
: Format the argument at index 0, which is 10 in this case (in recent versions of python, this can be left out if all the arguments appear in the same order as in the string).
0
: Fill extra space before the number with 0
s.
16
: The formatted number should be at least 16 characters long.
b
: Represent the number as binary.
The 16 is only a minimum width, so of course if you use a number that will not fit within 16 bits it will just print the longer representation.
If you want to support negative numbers then you will need extra consideration, because the -
symbol will count towards the 16-character width. A solution would be to use a space for the sign
option (before the 0):
>>> "{0: 017b}".format(2)
' 0000000000000010'
>>> "{0: 017b}".format(-2)
'-0000000000000010'
This places a space in the negative sign's place, ensuring that the string will always be the same length (number of bits plus 1). If you don't want the space, you could .lstrip()
the result.

- 7,564
- 2
- 28
- 37
Ignoring overflow (trying to encode a number in too few bits) you could do this:
>>> def dec_to_bin(n, bits):
return bin(n)[2:].zfill(bits)
>>> dec_to_bin(10, 4)
'1010'
>>> dec_to_bin(10, 8)
'00001010'

- 10,650
- 8
- 44
- 61