>> operator over/operator的优点

Abi*_*lam 2 java

使用>> operator over/operator有什么好处?它广泛用于我维护的代码中.例如, int width = previousWidth >> 2;

Jon*_*eet 7

当您想要将值移位一定数量的位时,理解起来要简单得多.例如:

byte[] bits = new byte[4];
bits[0] = (byte) (value >> 24);
bits[1] = (byte) (value >> 16);
bits[2] = (byte) (value >> 8);
bits[3] = (byte) (value >> 0);
Run Code Online (Sandbox Code Playgroud)

这显然是由不同数量的位移动的.你真的想用分裂来表达吗?

当然,当你真正想要的是除法时,为了便于阅读,你应该使用除法运算符.有些人可能会为了性能而使用位移,但与以往一样,对于大多数代码而言,可读性比微优化更重要.所以你的情况,如果有什么真正需要的是widthpreviousWidth除以4,代码应该*绝对反映:

int width = previousWidth / 4;
Run Code Online (Sandbox Code Playgroud)

在证明性能差异显着之后,我只使用了bithifting.