Unsigned integer bit field shift yields signed integer

前端 未结 1 656
执念已碎
执念已碎 2021-02-19 21:10

Let consider the following program test.c:

#include 

struct test {
    unsigned int a:5;
};

int main () {
    unsigned int i;
    s         


        
相关标签:
1条回答
  • 2021-02-19 21:28

    Integer promotions are applied to the operands of shift covered in the draft C99 standard section 6.5.7 Bitwise shift operators paragraph 3 which says (emphasis mine going forward):

    The integer promotions are performed on each of the operands.[...]

    and the integer promotion of a bit-field is covered in section 6.3.1.1 Boolean, characters, and integers paragraph 2 which says:

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

    and contains the following bullet:

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

    and then says:

    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. These are called the integer promotions.48) All other types are unchanged by the integer promotions.

    it was clarified in the draft C11 standard:

    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.

    So this is expected behavior.

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