gpt4 book ai didi

unsigned int 和 unsigned char 的比较

转载 作者:太空宇宙 更新时间:2023-11-04 01:34:26 27 4
gpt4 key购买 nike

我有一个无符号字符数组,例如Data[2]。我需要它来与返回 unsigned int 的函数的输出进行比较。

我尝试将 Data[2] 转换为 unsigned int,反之亦然。它没有用。

我想做的是:

if (Data[2] == ReadFlash2(40))
{
//Do Something.
}

ReadFlash2 是一个返回 unsigned int 的函数,而 Data[2] 是一个 unsigned char。

我尝试对它们中的每一个进行转换,但没有成功。

我做错了什么吗?我应该投哪一个,我应该投什么?

谢谢。

编辑:Readflash 函数的代码:

unsigned int ReadFlash2(unsigned int Addr) // use as Read Function 
{
pMem = (unsigned int*)MEM_STR_ADR;
pMem += Addr;
Nop();
return(*pMem);
}

最佳答案

你根本不需要强制转换它们,C 中与隐式提升相关的规则应该为你解决这个问题。

换句话说,将 unsigned charunsigned int 进行比较将首先提升 unsigned char 的兼容性,然后 进行比较。

C99 6.3.1.8 Usual arithmetic conversions 中都包含了这一切(在讨论浮点类型之后):

Otherwise, the integer promotions are performed on both operands.

Then the following rules are applied to the promoted operands:

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

...等等,但上面的最后一段是适用的。

如果类型如您所述,并且 Data[2] 实际上 与从 ReadFlash2(40) 返回的值相同>,那么它不是 C 环境,至少不符合标准。

关于unsigned int 和 unsigned char 的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17182292/

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