Two's complement: Difference between revisions

m
Made code moreC++ idiomatic.
m (Made code moreC++ idiomatic.)
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 <cstdint>
#include <iostream>
#include <iomanip>
Line 96 ⟶ 97:
#include <bitset>
 
std::string to_hex(const int32_t number) {
std::stringstream stream;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
Line 102 ⟶ 103:
}
 
std::string to_binary(const int32_t number) {
std::stringstream stream;
stream << std::bitset<16>(number);
Line 108 ⟶ 109:
}
 
int32_t twos_complement(const int32_t number) {
return ~number + 1;
}
Line 127 ⟶ 128:
<< std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl;
 
for ( const 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;
884

edits