Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Signed Decimal to binary

How do I convert a signed decimal integer to 16-bits binary in Python?
bin() function is pretty basic and just adds a "-" before the number.

My requirement is:
Suppose we have a number -4, then output should be 1000000000000100.
That is, MSB is sign bit and rest magnitude bits.

I have tried the common masking technique but it gives 2’s complement and extension of 1’s in the significant bits.
For example, print(bin(-7 & 0b1111111111111111).replace("0b",""))
Output: 1111111111111001

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Add leading zeros through the format, and then add sign bit according to the positive and negative:

>>> def to_bin(val):
...     b = bin(val).split('b')[1][-15:]
...     p = '0' if val >= 0 else '1'
...     return p + format(b, '>015')
...
>>> to_bin(-7)
'1000000000000111'
>>> to_bin(-4)
'1000000000000100'
>>> to_bin(4)
'0000000000000100'
>>> to_bin(2 ** 16)    # overflow
'0000000000000000'
>>> to_bin(2 ** 16 - 1)
'0111111111111111'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading