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?
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?
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);
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.