PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to convert to and from two's complement and sign & magnitude?

 July 20, 2022     bit-manipulation, integer, math, python, signed     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing