编译器如何实现位域算术

编译器如何实现位域算术

本文介绍了编译器如何实现位域算术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当询问如何做的问题wrapped N比特签署减法我得到了以下的回答:

When asking a question on how to do wrapped N bit signed subtraction I got the following answer:

template<int bits>
int
sub_wrap( int v, int s )
{
    struct Bits { signed int r: bits; } tmp;
    tmp.r = v - s;
    return tmp.r;
}

这很好,所有,但如何将一个编译器实现这一点?从this问题据我了解,访问位字段是多还是少一样做手工,但对于在这个例子中,当算术结合起来呢?难道是一样快,一个很好的手动位变换的方法吗?

That's neat and all, but how will a compiler implement this? From this question I gather that accessing bit fields is more or less the same as doing it by hand, but what about when combined with arithmetic as in this example? Would it be as fast as a good manual bit-twiddling approach?

如果任何人希望得到具体为编译器的作用,海湾合作委员会的答案将是巨大的。我试着读生成的程序集,但目前它是超越我。

An answer for "gcc" in the role of "a compiler" would be great if anyone wants to get specific. I've tried reading the generated assembly, but it is currently beyond me.

推荐答案

由于写入另一个问题,未签名的包装数学可以做的:

As written in the other question, unsigned wrapping math can be done as:

int tmp = (a - b) & 0xFFF;  /* 12 bit mask.  */

的一个(12位)位域会做到这些,符号或无符号。唯一的区别是,你可能会从编译器警告消息。

Writing to a (12bit) bitfield will do exactly that, signed or unsigned. The only difference is that you might get a warning message from the compiler.

有关的阅读的不过,你需要做的事情有点不同。

For reading though, you need to do something a bit different.

有关数学符号,它足以做到这一点:

For unsigned maths, it's enough to do this:

int result = tmp;  /* whatever bit count, we know tmp contains nothing else.  */

int result = tmp & 0xFFF;  /* 12bit, again, if we have other junk in tmp.  */

有关签署数学,额外的法宝是符号扩展:

For signed maths, the extra magic is the sign-extend:

int result = (tmp << (32-12)) >> (32-12); /* asssuming 32bit int, and 12bit value. */

所有这一切确实是复制位域的最高位在更广泛的INT(11位)。

All that does is replicate the top bit of the bitfield (bit 11) across the wider int.

这正是编译器做什么位域。无论您code他们用手工或位域是你的,只是确保你得到的幻数权利。

This is exactly what the compiler does for bitfields. Whether you code them by hand or as bitfields is up to you, but just make sure you get the magic numbers right.

(我没有读过的标准,但我怀疑,依靠位域做溢出正确的事情可能不是安全的?)

(I have not read the standard, but I suspect that relying on bitfields to do the right thing on overflow might not be safe?)

这篇关于编译器如何实现位域算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:14