Why is a number sign-extended when it is cast to an unsigned type?

前端 未结 1 518
长发绾君心
长发绾君心 2021-01-19 05:25

I was studying how C stores data in memory by bit patterns.
However I have confronted some issues when it comes to printf formatting.

I have saved

1条回答
  •  臣服心动
    2021-01-19 06:09

    In this expression

    (unsigned int) a
    

    the integer promotions are applied to the object a.

    From the C Standard (6.3.1.1 Boolean, characters, and integers)

    2 The following may be used in an expression wherever an int or unsigned int may be used:

    — An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.

    — A bit-field of type _Bool, int, signed int, or unsigned int.

    If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. 58) All other types are unchanged by the integer promotions.

    and

    3 The integer promotions preserve value including sign. As discussed earlier, whether a ‘‘plain’’ char is treated as signed is implementation-defined.

    If you want that in the result object after casting the character object woulf be represented as having the type unsigned char then you have to write

    (unsigned char) a
    

    As the value of the promoted expression (unsigned char) a can be represented in the type unsigned int then the second cast (to unsigned int) is not required. The C Standard allows to use arguments pf the type int instead of the type unsigned int if the value is represented in the both types. You could just write

    printf("a : %x , b : %x\n" , (unsigned char) a, (unsigned int) b);
    

    0 讨论(0)
提交回复
热议问题