【发布时间】:2015-11-22 00:22:50
【问题描述】:
所以我有一些经常运行的代码来评估旋转状态。它有两个字节,每个字节的范围是 0-3,对应一个方向(0=左,1=下,2=右,3=上),产生一个字节显示哪一步旋转它在(所以我们可以找出循环到下一个方向的两个方向)。请注意,这两个字节不应该相等,但如果发生这种情况,旋转值将设置为 -1。我知道位运算往往比分支运算快,所以我使用位运算来计算值。这是我目前所拥有的:
byte rotation = -1;
if(con1!=con2){
if((con1&0x1)==(con2&0x1))rotation=(byte) (4+(con1&0x1));
else{
rotation = (byte) ((con1^con2)>>1);
rotation = (byte) (rotation | (rotation==0x0?con1&0x2:((con1<<1)^con2))&0x2);
}
}
con1 和 con2 是两个输入字节。 rotation 为旋转字节,对应如下:
-1 = invalid input
0 = (┐), left and down (a 0 and a 1)
1 = (┌), down and right (a 1 and a 2)
2 = (└), right and up (a 2 and a 3)
3 = (┘), up and left (a 3 and a 0)
4 = (─), left and right (a 0 and a 2)
5 = (│), down and up (a 1 and a 3)
现在的问题是,有没有人有更快的方法来计算这个?
【问题讨论】:
标签: java rotation bit-manipulation bitwise-operators cycle