gpt4 book ai didi

c - 类型转换和位操作之谜

转载 作者:行者123 更新时间:2023-12-01 23:15:06 26 4
gpt4 key购买 nike

#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”的值是错误的?这里球和傻瓜取值从0到15,我试图将combined_value连接为{ball[4位]:傻瓜[4位]:[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 .

关于c - 类型转换和位操作之谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com