Two's complement: Difference between revisions
m
Improved formatting of output.
m (New post.) |
m (Improved formatting of output.) |
||
Line 91:
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>
Line 111 ⟶ 110:
int32_t twos_complement(int32_t number) {
return ~number + 1;
}
std::string to_upper_case(std::string str) {
for ( char& ch : str ) {
ch = toupper(ch);
}
return str;
}
Line 119 ⟶ 125:
<< std::setw(17) << "binary" << std::setw(25) << "two's complement" << std::endl;
std::cout << std::setw(6) << "-----------" << std::setw(12) << "--------"
<< std::setw(
for ( int32_t example : examples ) {
std::cout << std::setw(6) << example << std::setw(17) << to_upper_case(to_hex(example))
<< std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl;
}
Line 129 ⟶ 135:
{{ out }}
<pre>
----------- --------
0 00000000 0000000000000000 0
1 00000001 0000000000000001 -1
-1
42
</pre>
|