Issue
How do I convert a signed integer in two's complement representation to sign and magnitude representation and vice versa in python?
def twos_comp_to_sign_mag(twos_comp_int):
# function definition here
def sign_mag_to_twos_comp(sign_mag_int):
# function definition here
twos_comp_to_sign_mag(255) == 129
sign_mag_to_twos_comp(129) == 255
# Since:
# 255 in binary is 1111_1111 or -1 in two's complement notation
# 129 in binary is 1000_0001 or -1 in sign-magnitude notation
Solution
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
Answered By - Mark Ransom Answer Checked By - Marilyn (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.