C/C++有点摆弄
本着 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会尝试
或者,按照lijie在评论中的建议
如果
sgn
是0
,~sgn+1
也是0
代码>,所以pow2 ^ (~sgn+1) == pow2
。如果sgn
为1
,则(~sgn+1)
为0xFFFFFFFF
,并且(pow2 ^ ( ~sgn+1)) + sgn == -pow2
。I would try
or, as suggested by lijie in the comments
If
sgn
is0
,~sgn+1
is also0
, sopow2 ^ (~sgn+1) == pow2
. Ifsgn
is1
,(~sgn+1)
is0xFFFFFFFF
, and(pow2 ^ (~sgn+1)) + sgn == -pow2
.我突然想到:
不能保证它是否有效或是否聪明,这只是我脑海中突然出现的一个想法。
编辑:让我们把它的可读性降低一点(又名更紧凑):
Off the top of my head:
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):
我会改变接口并用左移代替乘法。 (使用指数代替 pow2)
I would change the interface and replace the multiplication by left shift. (Use exponent instead of pow2)
你可以做类似的事情(从链接)
x += ((pow2 ^ -sgn) + sgn)
You can do something like (from the link)
x += ((pow2 ^ -sgn) + sgn)