Skip to content

Instantly share code, notes, and snippets.

@timsonner
Last active March 7, 2023 23:30
Show Gist options
  • Select an option

  • Save timsonner/6558cd576d78acdfb82ca4d6ab04d404 to your computer and use it in GitHub Desktop.

Select an option

Save timsonner/6558cd576d78acdfb82ca4d6ab04d404 to your computer and use it in GitHub Desktop.
C++. See binary, hex, octal, and decimal representations of a number.
// Include headers for classes...
#include <iostream>
#include <iomanip>
#include <string>
#include <bitset>
// Classes from different namespaces...
using std::cout;
using std::cin;
using std::endl;
// Namespace containing utility functions for formatting numbers
namespace numutil {
// Using statements for convenient access to certain functions
using std::setw;
using std::setfill;
using std::oct;
using std::hex;
using std::bitset;
using std::to_string;
using std::uppercase;
// Prints the decimal representation of a number to the console
void printInDecimal(int num) {
cout << "Decimal: " << num << endl;
}
// Prints the octal representation of a number to the console
void printInOctal(int num) {
// Determine the minimum width needed for the output, so single digit numbers display correctly eg: 9 is displayed as 09.
int width = to_string(num).length(); // get length of the int
if (width == 1)
{
width++; // pad with an extra zero becauses its a single digit
}
// Use the octal manipulator and set the width and fill character for output
cout << "Octal: " << oct << setw(width + 1) << setfill('0') << num << endl;
}
// Prints the hexadecimal representation of a number to the console
void printInHexadecimal(int num) {
// Use the hexadecimal manipulator and set the width, fill character, and uppercase flag for output
cout << "Hexadecimal: " << "0x"<< uppercase << hex << setw(8) << setfill('0') << num << endl;
}
// Prints the binary representation of a number to the console
void printInBinary(int num) {
// The sizeof operator returns the size of the num variable in bytes, so we multiply by 8 to get the size in bits
cout << "Binary: " << bitset<sizeof(num)*8>(num) << endl;
}
}
// Main function...
int main() {
int num;
// Get input from user...
cout << "Enter a number: ";
cin >> num;
// Call the utility functions to print the number in different formats
numutil::printInDecimal(num);
numutil::printInOctal(num);
numutil::printInHexadecimal(num);
numutil::printInBinary(num);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment