C:uint16_t在gcc中的减法行为 [英] C: uint16_t subtraction behavior in gcc

查看:211
本文介绍了C:uint16_t在gcc中的减法行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图减去两个无符号整数并将结果与​​一个有符号整数(或文字)进行比较。当使用 unsigned int 类型时,行为与预期一致。当使用 uint16_t (来自 stdint.h )类型时,行为并不是我所期望的。使用gcc 4.5完成比较。

给出以下代码:

  unsigned int a; 
unsigned int b;

a = 5;
b = 20;

printf(%u \ n,(a-b)<10);

输出为0,这是我的预期。 a和b都是无符号的,并且b比a大,所以结果是一个大于10的大的无符号数。现在,如果我改变a和b来键入uint16_t:

  uint16_t a; 
uint16_t b;

a = 5;
b = 20;

printf(%u \ n,(a-b)<10);

输出是1.为什么是这样?在gcc中存储在int中的两个uint16_t类型之间的减法结果是什么?如果我将 10 更改为 10U ,则输出再次为0,这似乎支持这一点(如果减法结果为存储为一个int,并且与一个无符号整数进行比较,而减法结果将转换为一个unsigned int)。 >因为计算不是用低于int / unsigned int(char,short,unsigned short等;但不长,unsigned long等)的类型完成的,但它们首先被提升为int或unsigned int之一。 uint16_t在你的实现上可能是unsigned short,在你的实现中被提升为int。因此,计算结果为-15,小于10。



在以16位计算的较早实现中,int可能无法代表无符号短的所有值,因为它们都具有相同的位宽。这种实现必须将unsigned short提升为unsigned int。在这样的实现中,您的比较结果为0。


I'm trying to subtract two unsigned ints and compare the result to a signed int (or a literal). When using unsigned int types the behavior is as expected. When using uint16_t (from stdint.h) types the behavior is not what I would expect. The comparison was done using gcc 4.5.
Given the following code:

unsigned int a;
unsigned int b;

a = 5;
b = 20;

printf("%u\n", (a-b) < 10);

The output is 0, which is what I expected. Both a and b are unsigned, and b is larger than a, so the result is a large unsigned number which is greater than 10. Now if I change a and b to type uint16_t:

uint16_t a;
uint16_t b;

a = 5;
b = 20;

printf("%u\n", (a-b) < 10);

The output is 1. Why is this? Is the result of subtraction between two uint16_t types stored in an int in gcc? If I change the 10 to 10U the output is again 0, which seems to support this (if the subtraction result is stored as an int and the comparison is made against an unsigned int than the subtraction results will be converted to an unsigned int).

解决方案

Because calculations are not done with types below int / unsigned int (char, short, unsigned short etc; but not long, unsigned long etc), but they are first promoted to one of int or unsigned int. "uint16_t" is possibly "unsigned short" on your implementation, which is promoted to "int" on your implementation. So the result of that calculation then is "-15", which is smaller than 10.

On older implementations that calculate with 16bit, "int" may not be able to represent all values of "unsigned short" because both have the same bitwidth. Such implementations must promote "unsigned short" to "unsigned int". On such implementations, your comparison results in "0".

这篇关于C:uint16_t在gcc中的减法行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆