How to convert to and from two's complement and sign & magnitude?
You can only perform this kind of conversion on an integer with a fixed number of bits. I've made it a parameter to the function.
The two operations are complementary, you can use the same function to go both directions. You separate the sign bit, then complement the remainder and combine them back together.
def twos_comp_to_sign_mag(value, bits=8):
sign_bit = 1 << (bits - 1)
sign = value & sign_bit
mask = sign_bit - 1
if sign:
value = -(value & mask)
return (sign_bit & value) | (value & mask)
>>> twos_comp_to_sign_mag(255)
129
>>> twos_comp_to_sign_mag(129)
255