Search code examples
cbitwise-operatorsuint8t

Bitwise operations performed on an 8 bit unsigned int


In the following code, bitwise operations are performed on an 8-bit unsigned integer.

uint8_t i = 10;
uint8_t j = i>>2;

In this example, i is promoted to a signed int and value assigned to 8 bits unsigned int. Is it safe to int converted back to 8 bits unsigned int?


Solution

  • No.

    In arithmetic expressions, the lesser types are converted to int if possible, and otherwise to unsigned int (see 6.3.1.1p2).

    Practically,

    uint8_t i = 10;
    puts(_Generic(i>>2, uint8_t: "u8", int: "int", unsigned int: "uint"));
    

    should output "int", as should

    uint8_t i = 10, j = 2;
    puts(_Generic(i>>j, uint8_t: "u8", int: "int", unsigned int: "uint"));
    

    (In the former example, i would also get promoted to int because 2 is of type int and because usual arithmetic conversions would apply.)