Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

2's Compliment

Status
Not open for further replies.

perlfan

Technical User
Apr 18, 2002
17
US
I have an integer that needs converting. Basically I need to find it's 2's compliment and then use the first bit as the sign bit. Anybody know a good way to do it?
 
huh? [hammer] 'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
goBoating: There are three ways to represent negative numbers: ones-complement, twos-complement, and sign-magnitude.

In ones-complement, a negative A is obtained by bitwise-negating A. The leftmost bit is the sign of the number, positive is 0, negative is 1. So, using 4-bit numbers, 2 ~= 0010 and -2 ~= 1101.

In twos complement representation, negative numbers are represented by bitwise-negating the positive value, then adding one. Again, the leftmost bit is a sign bit: positive is 0, negative 1. 2 ~= 0010, -2 ~= 1110.

Sign-magitude, you just flip the leftmost sign bit to represent negation. 2 ~= 0010, -2 ~= 1010.



Perlfan, do you want to print as a string of 1s and 0s the given-bitwidth binary representation of the 2s-complement negation of a positive number?
 
Is this what you want?

my $num = -12;
my $bin = unpack("B32",pack("N", $num));
my $sign = ($bin =~ /^(\d)/)[0] ? "-": "+";
print "SIGN: $sign\n";
print "BNUM: $bin\n";

this prints

SIGN: -
BNUM: 11111111111111111111111111110100

For 32bit ints, of course.

jaa

 
For starters thanks to those who responded.

After I posted my question I got more info on the problem at hand. In a nutshell we have multiple computers communicating across an interface. One computer stores integers as signed magnitude (first bit is sign bit remaining bits are powers of two) while the other computer stores integers as 2's compliment. The problem with this is as bits came across the interface the integers derived were wrong for negative numbers.

The code below was how I transformed the incorrect integer created when interpreting a signed magnitude as a 2's compliment. Probably a more eloquent way but it got the job done.

my $bitstream = unpack("B32", pack("N", $incorrectint));
my $i;
my $num = 0;
for($i = 0; $i < 31; $i++){$num += chop($bitstream)*2**$i};
$num *= -1 if ($bitstream eq 1);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top