uint8_t iostream行为

时间:2013-03-08 14:47:37

标签: c++ c++11 iostream

摘要:我期待代码:cout<< uint8_t(0);打印“0”,但不打印任何内容。

长版本:当我尝试将uint8_t对象流式传输到cout时,我会使用gcc获得奇怪的字符。这是预期的行为吗?可能是因为uint8_t是某些基于字符的类型的别名吗?请参阅代码示例中的编译器/系统说明。

// compile and run with:
// g++ test-uint8.cpp -std=c++11 && ./a.out
//                    -std=c++0x (for older gcc versions)
/**
 * prints out the following with compiler:
 *     gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
 * on the system:
 *     Linux 3.7.9-101.fc17.x86_64
 * Note that the first print statement uses an unset uint8_t
 * and therefore the behaviour is undefined. (Included here for
 * completeness)

> g++ test-uint8.cpp -std=c++11 && ./a.out
>>>�<<<    >>>194<<<
>>><<<    >>>0<<<
>>><<<    >>>0<<<
>>><<<    >>>0<<<
>>><<<    >>>1<<<
>>><<<    >>>2<<<

 *
 **/

#include <cstdint>
#include <iostream>

void print(const uint8_t& n)
{
    std::cout << ">>>" << n                 << "<<<    "
              << ">>>" << (unsigned int)(n) << "<<<\n";
}

int main()
{
    uint8_t a;
    uint8_t b(0);
    uint8_t c = 0;
    uint8_t d{0};
    uint8_t e = 1;
    uint8_t f = 2;
    for (auto i : {a,b,c,d,e,f})
    {
        print(i);
    }
}

3 个答案:

答案 0 :(得分:14)

uint8_tunsigned char的别名,并且iostream对于打印字符而不是格式化数字的字符有特殊的重载。

转换为整数会抑制此现象。

答案 1 :(得分:6)

  

难道uint8_t是某些基于字符的类型的别名吗?

绝对。如果存在这样的类型,则必须是内置8位无符号整数类型的typedef。由于只有两种可能的8位无符号整数类型,char用于将其视为无符号和unsigned char的编译器,因此它必须是其中之一。除char大于8位的系统外,在这种情况下它不存在。

答案 2 :(得分:0)

正如其他人所指出的那样,unsigned char被视为operator<<。我有时会使用 流式传输的整数类型的位字段,以及整数,以避免必须转换或重载#include <iostream> struct WasteAbyte { unsigned short has_byte_range:8; }; struct Pos { unsigned short x:8; unsigned short y:8; }; int main() { WasteAbyte W = {255}; ++W.has_byte_range; std::cout << W.has_byte_range << std::endl; std::cout << sizeof(WasteAbyte) << std::endl; std::cout << sizeof(Pos) << std::endl; return 0; } ,但只有在不浪费空间的情况下,如下面的Pos结构:

0
2
2

输出:

"java.lang.RuntimeException: Unable to start activity ComponentInfo{hovi.akapbox/hovi.akapbox.CytatyActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."