简体   繁体   中英

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.

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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