C语言 将 int 转换为 uint8_t

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17882438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:01:34  来源:igfitidea点击:

converting int to uint8_t

cinttype-conversionuint8t

提问by Johan Elmander

is it a correct way to convert an intvalue to uint8_t:

这是将int值转换为的正确方法uint8_t

int x = 3; 
uint8_t y = (uint8_t) x;

assume that x will never be less than 0. Although gccdoes not give any warning for the above lines, I just wanted to be sure if it is correct to do it or is there a better way to convert int to uint8_t?

假设 x 永远不会小于 0。虽然gcc没有对以上几行发出任何警告,但我只是想确定这样做是否正确,或者是否有更好的方法将 int 转换为 uint8_t?

P.S. I use C on Linux if you are going to suggest a standard function

PS 如果您要建议标准功能,我在 Linux 上使用 C

回答by ouah

It is correct but the cast is not necessary:

这是正确的,但演员不是必需的:

uint8_t y = (uint8_t) x;

is equivalent to

相当于

uint8_t y = x;

xis implicitely converted to uint8_tbefore initialization in the declaration above.

xuint8_t在上面的声明中被隐式转换为 before 初始化。