RosettaCodeData/Task/Twos-complement/C++/twos-complement.cpp

43 lines
1.3 KiB
C++
Raw Permalink Normal View History

2023-07-09 17:42:30 -04:00
#include <cstdint>
2023-07-01 11:58:00 -04:00
#include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
2023-07-09 17:42:30 -04:00
std::string to_hex(const int32_t number) {
2023-07-01 11:58:00 -04:00
std::stringstream stream;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
return stream.str();
}
2023-07-09 17:42:30 -04:00
std::string to_binary(const int32_t number) {
2026-04-30 12:34:36 -04:00
std::stringstream stream;
stream << std::bitset<16>(number);
return stream.str();
2023-07-01 11:58:00 -04:00
}
2023-07-09 17:42:30 -04:00
int32_t twos_complement(const int32_t number) {
2026-04-30 12:34:36 -04:00
return ~number + 1;
2023-07-01 11:58:00 -04:00
}
std::string to_upper_case(std::string str) {
2026-04-30 12:34:36 -04:00
for ( char& ch : str ) {
ch = toupper(ch);
}
return str;
2023-07-01 11:58:00 -04:00
}
int main() {
2026-04-30 12:34:36 -04:00
std::vector<int32_t> examples = { 0, 1, -1, 42 };
2023-07-01 11:58:00 -04:00
2026-04-30 12:34:36 -04:00
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(20) << "----------------" << std::setw(20) << "----------------" << std::endl;
2023-07-01 11:58:00 -04:00
2026-04-30 12:34:36 -04:00
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;
}
2023-07-01 11:58:00 -04:00
}