简体   繁体   English

打印十六进制字符

[英]Printing hex characters

I would like to understand the results of printing out a char and an unsigned char.我想了解打印出一个字符和一个无符号字符的结果。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int8_t a = 0xA1;
    uint8_t b = 0xA1;
    printf("0x%x,", a);
    printf("0x%x,", b);
    std::cout << std::hex << a << ",";
    std::cout << std::hex << b << std::endl;
}

Result结果

0xffffffa1,0xa1,�,� 

I don't understand why the signed char turns into an uint or int, and why std::hex fails miserably.我不明白为什么有符号的 char 变成了 uint 或 int,以及为什么 std::hex 惨遭失败。

int8_t a = 0xA1; causes signed overflow, thus the behavior is undefined.导致有符号溢出,因此行为未定义。 If you turned on correct compiler flags, you'd get something like:如果你打开了正确的编译器标志,你会得到类似的东西:

error: overflow in conversion from 'int' to 'int8_t' {aka 'signed char'} changes value from '161' to '-95' [-Werror=overflow]

    8 |     int8_t a = 0xA1;

      |                ^~~~

Besides, %x expects an unsigned int .此外, %x需要一个unsigned int This also causes undefined behavior.这也会导致未定义的行为。 You meant to do something like:你的意思是做这样的事情:

#include <iostream>

int main()
{
    int8_t a = 42; // Doesnt overflow
    uint8_t b = 42;
    std::printf("%#x,", static_cast<unsigned int>(a));
    std::printf("%#x,", static_cast<unsigned int>(b));
    std::cout << std::hex << static_cast<unsigned int>(a) << ",";
    std::cout << std::hex << static_cast<unsigned int>(b) << std::endl;
}

Output: 0x2a,0x2a,2a,2a输出: 0x2a,0x2a,2a,2a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM