How to print an unsigned char in C?

前端 未结 6 2241
梦如初夏
梦如初夏 2020-11-29 02:34

I am trying to print char as positive value:

char ch = 212;
printf(\"%u\", ch);

but I get:

4294967252

How

6条回答
  •  自闭症患者
    2020-11-29 02:43

    This is because in this case the char type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u interprets the number as a large positive number:

    212 = 0xD4
    

    When it is sign-extended, FFs are pre-pended to your number, so it becomes

    0xFFFFFFD4 = 4294967252
    

    which is the number that gets printed.

    Note that this behavior is specific to your implementation. According to C99 specification, all char types are promoted to (signed) int, because an int can represent all values of a char, signed or unsigned:

    6.1.1.2: If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int.

    This results in passing an int to a format specifier %u, which expects an unsigned int.

    To avoid undefined behavior in your program, add explicit type casts as follows:

    unsigned char ch = (unsigned char)212;
    printf("%u", (unsigned int)ch);
    


    * In general, the standard leaves the signedness of char up to the implementation. See this question for more details.

提交回复
热议问题