猿问

如何通过cout将字符输出为整数?

#include <iostream>


using namespace std;


int main()

{  

    char          c1 = 0xab;

    signed char   c2 = 0xcd;

    unsigned char c3 = 0xef;


    cout << hex;

    cout << c1 << endl;

    cout << c2 << endl;

    cout << c3 << endl;

}

我期望输出如下:


ab

cd

ef

但是,我什么也没得到。


我猜这是因为cout始终将'char','signed char'和'unsigned char'视为字符,而不是8位整数。但是,“ char”,“ signed char”和“ unsigned char”都是整数类型。


所以我的问题是:如何通过cout将字符输出为整数?


PS:static_cast(...)难看,需要更多工作来修剪多余的位。


鸿蒙传说
浏览 1259回答 3
3回答

尚方宝剑之说

将它们强制转换为整数类型(以及相应的位掩码!),即:#include <iostream>using namespace std;int main(){&nbsp;&nbsp;&nbsp; &nbsp; char&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c1 = 0xab;&nbsp; &nbsp; signed char&nbsp; &nbsp;c2 = 0xcd;&nbsp; &nbsp; unsigned char c3 = 0xef;&nbsp; &nbsp; cout << hex;&nbsp; &nbsp; cout << (static_cast<int>(c1) & 0xFF) << endl;&nbsp; &nbsp; cout << (static_cast<int>(c2) & 0xFF) << endl;&nbsp; &nbsp; cout << (static_cast<unsigned int>(c3) & 0xFF) << endl;}

繁华开满天机

关于什么:char c1 = 0xab;std::cout << int{ c1 } << std::endl;简洁,安全,并且产生与其他方法相同的机器代码。
随时随地看视频慕课网APP
我要回答