如何将分裂成按位移位两当电源? [英] How to turn a division into a bitwise shift when power of two?

查看:92
本文介绍了如何将分裂成按位移位两当电源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的部门,我需要经常做:

I have the following division that I need to do often:

int index = pos / 64;

司可能是昂贵的,在CPU的水平。我希望有一种方法可以做到这一点与按位转变。我也想了解,你可以从分工转移,换句话说,我不希望只是记住按位EX pression。

Division can be expensive in the cpu level. I am hoping there is a way to do that with bitwise shift. I would also like to understand how you can go from division to shift, in other words, I don't want to just memorize the bitwise expression.

推荐答案

INT指数= POS>> 6 将做到这一点,但这是不必要的。任何合理的编译器会做这样的事情你。当然,太阳/ Oracle的编译器。

int index = pos >> 6 will do it, but this is unnecessary. Any reasonable compiler will do this sort of thing for you. Certainly the Sun/Oracle compiler will.

一般的规则是, I /(2 ^ N)可与实施I>> ñ。同样 I *(2 ^ N) I<< ñ

The general rule is that i/(2^n) can be implemented with i >> n. Similarly i*(2^n) is i << n.

您需要用负数再presentation担心,如果签署。例如。二进制补码产生合理的结果(如果右移是算术 - 符号位复制)。签名幅度没有。

You need to be concerned with negative number representation if i is signed. E.g. twos-complement produces reasonable results (if right shift is arithmetic--sign bit copied). Signed magnitude does not.

这篇关于如何将分裂成按位移位两当电源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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