1 byte integer data type

心已入冬 提交于 2019-12-13 12:06:53

问题


I wrote the following code:

 #include <iostream>
 #include <iomanip>
 #include <stdint.h>

 using namespace std;

 int main()
 {
     uint8_t c;

     cin  >> hex >> c;
     cout << dec << c;

     return 0;
 }

But when I input c—hex for 12—the output is also c. I was expecting 12. Later I learned that:

uint8_t is usually a typedef for unsigned char. So it's actually reading c as ASCII 0x63.

Is there a 1 byte integer which behaves as an integer while doing I/O and not as char?


回答1:


Not that I know of.

You could do the I/O using a wider integer type, and use range checking and casting as appropriate.




回答2:


I'm afraid I don't know of a way either, but reading a hex number into an integer type can be accomplished as follows:

#include <iostream>
using namespace std;

int main () {
    short c;
    cin >> std::hex >> c;
    cout << c << endl;
    return 0;
}


来源:https://stackoverflow.com/questions/13804591/1-byte-integer-data-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!