Two's complement: Difference between revisions

m
New post.
m (Minor tidy up.)
m (New post.)
Line 85:
<syntaxhighlight lang="c">int a = 3;
a = -a;</syntaxhighlight>
 
=={{header|C++}}==
In C++ the two's complement of an integer 'n' is its arithmetic negation '-n'.
 
The two's complement of an integer 'n' can also be calculated by adding 1 to its bitwise complement '~n'.
<syntaxhighlight lang="c++">
 
#include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
 
std::string to_hex(int32_t number) {
std::stringstream stream;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
return stream.str();
}
 
std::string to_binary(int32_t number) {
std::stringstream stream;
stream << std::bitset<16>(number);
return stream.str();
}
 
int32_t twos_complement(int32_t number) {
return ~number + 1;
}
 
int main() {
std::vector<int32_t> examples = { 0, 1, -1, 42 };
 
std::cout << std::setw(9) << "decimal" << std::setw(12) << "hex"
<< std::setw(17) << "binary" << std::setw(25) << "two's complement" << std::endl;
std::cout << std::setw(6) << "-----------" << std::setw(12) << "--------"
<< std::setw(17) << "----------" << std::setw(23) << "----------------" << std::endl;
 
for ( int32_t example : examples ) {
std::cout << std::setw(6) << example << std::setw(17) << to_hex(example)
<< std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
decimal hex binary two's complement
----------- -------- ---------- ----------------
0 00000000 0000000000000000 0
1 00000001 0000000000000001 -1
-1 ffffffff 1111111111111111 1
42 0000002a 0000000000101010 -42
</pre>
 
=={{header|Delphi}}==
908

edits