c++ - Trouble with a Two's Complement Function -
trying implement function homecoming two's complement of string of bits. i've tried 2 varieties , odd results.
version 1 (does inversion not "+1"): string twoscomp(signed int number) {
string twoscomp(signed int number) { if ( number == 0 ) { homecoming "1"; } if ( number == 1 ) { homecoming "0"; } if ( number % 2 == 0 ) { homecoming twoscomp(number / 2) + "1"; } else { homecoming twoscomp(number / 2) + "0"; } }
version 2 (inverts , attempts "+1" doesn't right)
string twoscomp(signed int number) { bool bit = 0; int size = 3; // not sure this, value -32768 32767 string twos; number = ~abs(number) + 1; for(int = 0; < size; i++) { //get right-most bit bit = number & 1; if(bit) { twos += '1'; } else { twos += '0'; } //shift bits right 1 place number >>= 1; } homecoming twos; } // end twoscomp
i've been trying various iterations of both of these functions. i'm running out of steam on this. if has improve alternative -- i'm open suggestions @ point.
how (abs(number) ^ 0xffffffff) + 1
, , turning value string?
edit: also, why size = 3
? ints 32 bits, usually
c++ bit-manipulation twos-complement
No comments:
Post a Comment