简体   繁体   English

C unsigned int比较-环绕自定义位数

[英]C unsigned int comparison - wrap around on custom bit number

I am reading a 24-bit value, presently into a uint32_t variable. 我正在读取一个24位值,当前是一个uint32_t变量。

After bashing my head against the wall calculating the difference between two such variables, and thinking "it's unsigned! Why is this overflow a problem?!", I realised the values are overflowing short of the size of the variable containing them. 用力撞墙计算了两个这样的变量之间的差,然后想到“它是无符号的!为什么这个溢出是个问题?!”之后,我意识到这些值溢出了小于包含它们的变量的大小。

This is a counter, so one is known to be 'larger' than the other, though may have overflowed. 这是一个计数器,因此尽管其中一个溢出,但已知一个比另一个“更大”。

Thus, 0x1 - 0x2 = 0xFFFFFFFF , but should be 0x00FFFFFF . 因此, 0x00FFFFFF 0x1 - 0x2 = 0xFFFFFFFF ,但应为0x00FFFFFF

How should I best deal with this? 我该如何最好地应对?

  • Define a type uint24 ; 定义类型uint24
  • if / else on which is larger before doing the appropriate arithmetic; if / else在进行适当的算术运算之前,取更大的值;
  • Something else I haven't thought of? 还有我没想到的吗?

'best' should be interpreted as 'best practices'/'most readable'/'safest'. “最佳”应解释为“最佳实践” /“最易读” /“最安全”。

To subtract (or add) two numbers and have the result wrap around the range of an unsigned 24-bit number, do a binary-and of the result with 0xFFFFFF , ie (xy) & 0xFFFFFF . 要减去(或相加)两个数字并使结果环绕在无符号的24位数字范围内,请对结果进行二进制与运算,即0xFFFFFF ,即(xy) & 0xFFFFFF For example: 例如:

(0x1 - 0x2) & 0xFFFFFF == 0xFFFFFF

At first, you can use compare operator != , == , > , >= , < and <= . 首先,您可以使用比较运算符!===>>=<<= you don't need do such as num1 - num2 if you want to compare... 如果要比较,则不需要执行num1 - num2 ...

Anyway, if it's really necesaary, just use bitwise AND 无论如何,如果确实需要,请使用按位AND

uint32_t n1 = 1, n2 = 5;
printf("0x%08x", (n1 - n2) & 0x00ffffff);

(live example) (实时示例)

Output: 输出:

0x00fffffc

As you know, 0xfffffc means -4 in 24-bit signed integer. 如您所知, 0xfffffc表示24位带符号整数中的-4

(Notice that 2's complement is not specified by C standard; my code may not work in non-2's complement system.) (请注意,C标准指定2的补码;我的代码可能无法在非2的补码系统中工作。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM