Trying to implement a function to return the two’s complement of a string of bits. I’ve tried two varieties and get odd results.
Version 1 (does the inversion but not the “+1”):
string twosComp(signed int number) {
string twosComp(signed int number) {
if ( number == 0 ) { return "1"; }
if ( number == 1 ) { return "0"; }
if ( number % 2 == 0 ) {
return twosComp(number / 2) + "1";
}
else {
return twosComp(number / 2) + "0";
}
}
Version 2 (inverts and attempts “+1” but doesn’t always get it right)
string twosComp(signed int number) {
bool bit = 0;
int size = 3; // not sure what to do about this, value could be -32768 to 32767
string twos;
number = ~abs(number) + 1;
for(int i = 0; i < size; i++) {
//Get right-most bit
bit = number & 1;
if(bit) {
twos += '1';
}
else {
twos += '0';
}
//Shift all bits right one place
number >>= 1;
}
return twos;
} // end twosComp
I’ve been trying various iterations of both of these functions. I’m running out of steam on this. If anyone has a better option — I’m VERY open to suggestions at this point.
how about
(abs(number) ^ 0xffffffff) + 1, and then turning that value into a string?edit: also, why is
size = 3? ints are 32 bits, usually