Two's complement: Difference between revisions

Content added Content deleted
m (Made code moreC++ idiomatic.)
Line 91: Line 91:
The two's complement of an integer 'n' can also be calculated by adding 1 to its bitwise complement '~n'.
The two's complement of an integer 'n' can also be calculated by adding 1 to its bitwise complement '~n'.
<syntaxhighlight lang="c++">
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iostream>
#include <iostream>
#include <iomanip>
#include <iomanip>
Line 96: Line 97:
#include <bitset>
#include <bitset>


std::string to_hex(int32_t number) {
std::string to_hex(const int32_t number) {
std::stringstream stream;
std::stringstream stream;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
Line 102: Line 103:
}
}


std::string to_binary(int32_t number) {
std::string to_binary(const int32_t number) {
std::stringstream stream;
std::stringstream stream;
stream << std::bitset<16>(number);
stream << std::bitset<16>(number);
Line 108: Line 109:
}
}


int32_t twos_complement(int32_t number) {
int32_t twos_complement(const int32_t number) {
return ~number + 1;
return ~number + 1;
}
}
Line 127: Line 128:
<< std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl;
<< std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl;


for ( int32_t example : examples ) {
for ( const int32_t& example : examples ) {
std::cout << std::setw(6) << example << std::setw(17) << to_upper_case(to_hex(example))
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;
<< std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl;