The decimal, octal and hexadecimal representation

2020-08-01 05:57发布

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

标签: c++
2条回答
对你真心纯属浪费
2楼-- · 2020-08-01 06:37

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";
}
查看更多
冷血范
3楼-- · 2020-08-01 06:38

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;
}
查看更多
登录 后发表回答