双到int转换后面的场景? [英] Double to int conversion behind the scene?

查看:108
本文介绍了双到int转换后面的场景?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道发生在幕后的事情,将double转换为int,说int(5666.1)?这是比父类的一个子类的static_cast更昂贵吗?因为int和double的表示是根本不同的,因为在过程中会创建临时表,并且也很昂贵。

I am just curious to know what happens behind the scene to convert a double to int, say int(5666.1) ? Is that going to be more expensive than a static_cast of a child class to parent? Since the representation of the int and double are fundamentally different is there going to be temporaries created during the process and expensive too.

推荐答案

任何具有本地浮点的CPU都将有一条将浮点数转换为整数数据的指令。该操作可以从几个周期到许多。通常有用于FP和整数的单独的CPU寄存器,因此您必须随后将整数移动到整数寄存器,然后才能使用它。这可能是另一种操作,可能是昂贵的。请参阅处理器手册。

Any CPU with native floating point will have an instruction to convert floating-point to integer data. That operation can take from a few cycles to many. Usually there are separate CPU registers for FP and integers, so you also have to subsequently move the integer to an integer register before you can use it. That may be another operation, possibly expensive. See your processor manual.

PowerPC明显不包括将FP寄存器中的整数移动到整数寄存器的指令。必须有一个存储从FP到内存和加载到整数。因此,您可以说创建了一个临时变量。

PowerPC notably does not include an instruction to move an integer in an FP register to an integer register. There has to be a store from FP to memory and load to integer. You could therefore say that a temporary variable is created.

在没有硬件FP支持的情况下,该数字必须解码。 IEEE FP格式是:

In the case of no hardware FP support, the number has to be decoded. IEEE FP format is:

sign | exponent + bias | mantissa

要进行转换,您必须执行

To convert, you have to do something like

// Single-precision format values:
int const mantissa_bits = 23; // 52 for double.
int const exponent_bits = 8; // 11 for double.
int const exponent_bias = 127; // 1023 for double.

std::int32_t ieee;
std::memcpy( & ieee, & float_value, sizeof (std::int32_t) );
std::int32_t mantissa = ieee & (1 << mantissa_bits)-1 | 1 << mantissa_bits;
int exponent = ( ieee >> mantissa_bits & (1 << exponent_bits)-1 )
             - ( exponent_bias + mantissa_bits );
if ( exponent <= -32 ) {
    mantissa = 0;
} else if ( exponent < 0 ) {
    mantissa >>= - exponent;
} else if ( exponent + mantissa_bits + 1 >= 32 ) {
    overflow();
} else {
    mantissa <<= exponent;
}
if ( ieee < 0 ) mantissa = - mantissa;
return mantissa;

也就是几个开箱说明和换档。

I.e., a few bit unpacking instructions and a shift.

这篇关于双到int转换后面的场景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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