为什么 int -> hex/oct/bin 的转换在输出中打印为纯十进制值?

Why does conversion of int -> hex/oct/bin print as plain decimal value in output?

#include <iostream>
#include <sstream>

using namespace std;

int main() {
     // <variables>
     int t = 0b11011101;

     stringstream aa;

     int n;
     string hexed;
     int hexedNot;
     // </variables>

     aa << t;
     aa >> n;
     cout << n << endl; // output 221
     aa.clear();

     aa << hex << n;
     aa >> hexed;
     aa.clear();

     aa << hex << n;
     aa >> hexedNot;
     cout << hexed << endl; // output dd

     cout << hexedNot; // output 221

     return 2137;
}

我想使用 stringstream 将 int 小数转换为 hex/oct/bin int,但我不知道如何正确处理它。如果我尝试将它转换为包含十六进制的字符串,没问题,但是当我尝试对整数执行相同操作时,它就不起作用了。有任何想法吗?我不会使用 c++11,我想以一种非常简单的方式来做。

我知道我可以使用 cout << hex << something;,但这只会改变我的输出,它不会将十六进制值写入我的变量。

std::string hexed; 是从 std::stream 中读取的,您在将 n 的十六进制表示形式注入流后读取的位置:

 aa << hex << n;

下一步操作

 aa >> hexed;

从流中读取到 std::string 变量。因此

cout << hexed << endl; // output dd

你好像误会了:

I know that I can use cout << hex << something;, but that would just change my output and it wouldn't write the hexified value into my variable.

在 C++ 或任何其他编程语言中,没有像 "hexified value" 这样的东西。只有(整数).

整数是整数,它们在input/output中的表示是不同的鱼缸:

它不直接绑定到它们的变量类型或它们初始化的表示,而是你告诉 std::istream/std::ostream 做什么。

要在终端上打印 221 的十六进制表示,只需写入

cout << hex << hexedNot;

关于您的评论:

but I want to have a variable int X = 0xDD or int X = 0b11011101 if that's possible. If not, I'll continue to use the cout << hex << sth; like I always have.

当然这些都是可以的。你应该尝试

而不是坚持他们的文本表示
int hexValue = 0xDD;
int binValue = 0b11011101;
if(hexValue == binValue) {
    cout << "Wow, 0xDD and 0b11011101 represent the same int value!" << endl;
}

不要混淆presentation and content

整数(与所有其他值一样)以二进制形式存储在计算机内存中 ("content")。 cout 是否以二进制、十六进制或十进制打印,只是一个格式化问题 ("representation")。 0b110111010xdd221都是相同数字的不同表示

C++ 或我所知道的任何其他语言都不会使用整型变量存储格式信息。但是您始终可以创建自己的类型来做到这一点:

// The type of std::dec, std::hex, std::oct:
using FormattingType = std::ios_base&(&)(std::ios_base&);

class IntWithRepresentation {
public:
  IntWithRepresentation(int value, FormattingType formatting)
  : value(value), formatting(formatting) {}

  int value;
  FormattingType formatting;
};

// Overload std::cout <<
std::ostream& operator<<(std::ostream& output_stream, IntWithRepresentation const& i) {
  output_stream << i.formatting << i.value;
  return output_stream;
}

int main() {
  IntWithRepresentation dec = {221, std::dec};
  IntWithRepresentation hex = {0xdd, std::hex};
  IntWithRepresentation oct = {221, std::oct};

  std::cout << dec << std::endl;
  std::cout << hex << std::endl;
  std::cout << oct << std::endl;
}