#include <stdio.h>
#include <stdint.h>
typedef unsigned char       uint8_t;
typedef short               int16_t;
typedef unsigned short      uint16_t;
typedef int                 int32_t;
typedef unsigned int        uint32_t;
int main(){
    uint8_t ball;
    uint8_t fool;
    ball=((unsigned char)13);
    fool=((unsigned char)14);
    uint16_t combined_value1=((uint16_t)ball)<<12+((uint16_t)fool)<<8; // WRONG ONE
    uint16_t combined_value2=((uint16_t)ball<<12)+((uint16_t)fool<<8);
    printf("%hu\n",(uint16_t)combined_value1);
    printf("%hu\n",(uint16_t)combined_value2);
    return 0;
}

为什么“combined_value1”的值错误?在这里,ball和fool的取值范围是0到15,我正在尝试将combined_value连接为{ball [4 bits]:fool [4 bits]:[8个零位]}。

最佳答案

+具有比<<高的precedence,因此

((uint16_t)ball)<<12+((uint16_t)fool)<<8;

被评估为
((uint16_t)ball) << (12+((uint16_t)fool)) << 8;

请注意,在这种情况下,(uint16_t)强制转换没有多大意义,因为在此之后会升级为int。相反,考虑
uint16_t combined_value = (uint16_t)((ball<<12) + (fool<<8));

还有其他一些多余的铸件。正如 @StoryTeller 所建议的那样,最好包含stdint.h

08-15 22:22