The decimal, octal and hexadecimal representation

2020-08-01 06:44发布

问题:

How can I express the value of an integer using decimal, octal or hexadecimal representation? (I would prefer only iostream usage)

回答1:

Assuming you just want to see them, for your own reference. Though storing them in a variable is "just a shot away".

#include <iostream>
using namespace std;

int main () {
  int n;
  n=70;
  cout << hex << n << endl;
  cout << dec << n << endl;
  cout << oct << n << endl;
  return 0;
}


回答2:

By "decimal integer" I hope you mean a string that uses decimal to represent an integer. Integer types, like int, do not have a base. Or if you insist that they must have a base because of their internal representation then the base is always 2. String representations of integers, now those have a base.

std::istringstream iss(std::string("123"));
int i;
if (iss >> i) {
    std::cout << "read a decimal integer!\n";
    std::cout << "here it is in decimal: " << i << "\n";
    std::cout << "here it is in hex: " << std::hex << i << "\n";
    std::cout << "here it is in octal: " << std::oct << i << "\n";
}


标签: c++