gpt4 book ai didi

c++ - Visual C++ 生成 DIV 而不是 IDIV(x86,整数运算)

转载 作者:太空狗 更新时间:2023-10-29 20:06:36 25 4
gpt4 key购买 nike

我在这里使用 Visual C++ 2008 (9.x),当我遇到编译器生成 DIV 而不是 IDIV 时,我正在准备一个定点值。我将代码折叠成一小段以准确重现:

short a = -255;
short divisor16 = 640; // unsigned, 16-bit
unsigned int divisor32 = 640; // unsigned, 32-bit
unsigned short s_divisor16 = 640; // signed, 16-bit
int s_divisor32 = 640; // signed, 32-bit
int16_t test1 = (a<<8)/divisor16; // == -102, generates IDIV -> OK
int16_t test2 = (a<<8)/s_divisor16; // == -102, generates IDIV -> OK
int16_t test3 = (a<<8)/divisor32; // == bogus, generates DIV -> FAIL!
int16_t test4 = (a<<8)/s_divisor32; // == -102, generates IDIV -> OK

int bitte_ein_breakpoint=1;

我不会用简单的拆卸来打扰你。

现在,我想知道是什么让编译器在第三种 (test3) 情况下选择 DIV 而不是 IDIV,而不是采用快捷方式,只是更改除数的类型(它是一个函数参数,unsigned int numPixels),因为它不这样做所以有了一个无符号的 16 位除数,实际上没有任何东西需要无符号算术。至少那是我的想法,我希望我是错的:)

最佳答案

/ 生成的代码运算符取决于操作数。

首先,表达式 (a << 8)类型为 int ,因为对每个操作数执行整数提升(ISO C99,6.5.7p3),然后操作是int << int ,结果为 int .

现在有四个表达式:

  1. int / short : 右侧提升为 int ,因此 idiv指导。
  2. int / unsigned short : 右侧提升为 int ,因此 idiv指导。
  3. int / unsigned int : 左侧 提升为 unsigned int ,因此 div指导。
  4. int / int : 没有任何提升,因此 idiv指导是适当的。

整数提升在 ISO C99 6.3.1.1p3 中定义:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions..

关于c++ - Visual C++ 生成 DIV 而不是 IDIV(x86,整数运算),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7131764/

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