eldenlord9394
eldenlord9394

Reputation: 33

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

Upvotes: 3

Views: 916

Answers (1)

Mechanic Pig
Mechanic Pig

Reputation: 7736

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'

Upvotes: 3

Related Questions