gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:32:27 24 4
gpt4 key购买 nike

#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 整数,但我不知道如何正确处理它。如果我尝试将它转换为包含十六进制的字符串,没问题,但是当我尝试对整数执行相同操作时,它就不起作用了。有任何想法吗?我不会使用 c++11,但我想以一种非常简洁和简单的方式来使用它。

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

最佳答案

std::string hexed;std::stream 读取,您在注入(inject) 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” 这样的东西。只有(整数)

整数就是整数,它们在输入/输出中的表示完全不同:

它不直接绑定(bind)到它们的变量类型或它们初始化的表示形式,而是你告诉 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;
}

关于c++ - 为什么 int -> hex/oct/bin 的转换在输出中打印为纯十进制值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35101899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com