C/C++有点摆弄

发布于 2024-10-03 23:52:44 字数 521 浏览 2 评论 0原文

本着 graphics.stanford.edu/~seander/bithacks.html 的精神我需要解决以下问题:

int x; 
int pow2; // always a positive power of 2
int sgn;  // always either 0 or 1
// ...
// ...
if(sgn == 0)
    x -= pow2;
else
    x += pow2;

当然我需要避免条件。到目前为止,我想出的最好的方法是,

x -= (1|(~sgn+1))*pow2

但这涉及乘法,我也想避免这种情况。提前致谢。

编辑:谢谢大家,

x -= (pow2^-sgn) + sgn

似乎可以解决问题!

in the spirit of graphics.stanford.edu/~seander/bithacks.html I need to solve the following problem:

int x; 
int pow2; // always a positive power of 2
int sgn;  // always either 0 or 1
// ...
// ...
if(sgn == 0)
    x -= pow2;
else
    x += pow2;

Of course I need to avoid the conditional. So far the best I came up with is

x -= (1|(~sgn+1))*pow2

but that involves a multiplication which I also would like to avoid. Thanks in advance.

EDIT: Thanks all,

x -= (pow2^-sgn) + sgn

seems to do the trick!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

微暖i 2024-10-10 23:52:44

我会尝试

x -= (pow2 ^ (~sgn+1)) + sgn

或者,按照lijie在评论中的建议

x -= (pow2 ^ -sgn) + sgn

如果sgn0~sgn+1也是0代码>,所以pow2 ^ (~sgn+1) == pow2。如果sgn1,则(~sgn+1)0xFFFFFFFF,并且(pow2 ^ ( ~sgn+1)) + sgn == -pow2

I would try

x -= (pow2 ^ (~sgn+1)) + sgn

or, as suggested by lijie in the comments

x -= (pow2 ^ -sgn) + sgn

If sgn is 0, ~sgn+1 is also 0, so pow2 ^ (~sgn+1) == pow2. If sgn is 1, (~sgn+1) is 0xFFFFFFFF, and (pow2 ^ (~sgn+1)) + sgn == -pow2.

恍梦境° 2024-10-10 23:52:44
mask = sgn - 1; // generate mask: sgn == 0 => mask = -1, sgn == 1 => mask = 0

x = x + (mask & (-pow2)) + (~mask & (pow2)); // use mask to select +/- pow2 for addition
mask = sgn - 1; // generate mask: sgn == 0 => mask = -1, sgn == 1 => mask = 0

x = x + (mask & (-pow2)) + (~mask & (pow2)); // use mask to select +/- pow2 for addition
暗地喜欢 2024-10-10 23:52:44

我突然想到:

int subMask = sgn - 1;
x -= pow2 & subMask;
int addMask = -sgn;
x += pow2 & addMask;

不能保证它是否有效或是否聪明,这只是我脑海中突然出现的一个想法。

编辑:让我们把它的可读性降低一点(又名更紧凑):

x += (pow2 & -sgn) - (pow2 & (sgn-1)); 

Off the top of my head:

int subMask = sgn - 1;
x -= pow2 & subMask;
int addMask = -sgn;
x += pow2 & addMask;

No guarantees on whether it works or whether this is smart, this is just a random idea that popped into my head.

EDIT: let's make this a bit less readable (aka more compact):

x += (pow2 & -sgn) - (pow2 & (sgn-1)); 
岁月流歌 2024-10-10 23:52:44

我会改变接口并用左移代替乘法。 (使用指数代替 pow2)

I would change the interface and replace the multiplication by left shift. (Use exponent instead of pow2)

旧竹 2024-10-10 23:52:44

你可以做类似的事情(从链接)
x += ((pow2 ^ -sgn) + sgn)

You can do something like (from the link)
x += ((pow2 ^ -sgn) + sgn)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文