我一直在为我的计算机组织类(class)开发不同的项目,并且我们一直在研究 BitWise 操作。我们当前的任务是为 java 编写一个自制的“rotateLeft”方法。
虽然 java 已经有了 Integer.rotateLeft,但我当前的任务是编写一个程序来使用该程序。
注意:int 变量等于这些位字符串
x1 = 3 = 00000000000000000000000000000011
x2 = -11= 1111111111111111111111111111110101
我当前的计划是:
public class Demo
{
public static void main(String[]args)
{
int x1=3, x2=-11;
System.out.print("x1: ");
BitWise.printbit(x1);
System.out.print("rotateLeft(x1,2): ");
BitWise.printbit(rotateLeft(x1,2));
System.out.print("x2: ");
BitWise.printbit(x2);
System.out.print("rotateLeft(x2,2): ");
BitWise.printbit(rotateLeft(x2,2));
}
public static int rotateLeft(int i, int distance)
{
int mask= i>>distance;
return mask;
}
}
此操作适用于 x1 位模式,但是,它只是移位位,而不是实际旋转它们。
有什么建议吗?
最佳答案
这对我有用:
public static void main(String[] args) {
int x1 = 3;
int x2 = -11;
int x1IntegerRotated = Integer.rotateLeft(x1, 2);
int x1SelfRotated = rotateLeft(x1, 2);
System.out.printf("x1 = %d(%s)%n", x1, printIntBitwise(x1));
System.out.printf("x1IntegerRotated = %d(%s)%n", x1IntegerRotated, printIntBitwise(x1IntegerRotated));
System.out.printf("x1SelfRotated = %d(%s)%n", x1SelfRotated, printIntBitwise(x1SelfRotated));
System.out.println();
int x2IntegerRotated = Integer.rotateLeft(x2, 2);
int x2SelfRotated = rotateLeft(x2, 2);
System.out.printf("x2 = %d(%s)%n", x2, printIntBitwise(x2));
System.out.printf("x2IntegerRotated = %d(%s)%n", x2IntegerRotated, printIntBitwise(x2IntegerRotated));
System.out.printf("x2SelfRotated = %d(%s)%n", x2SelfRotated, printIntBitwise(x2SelfRotated));
}
private static int rotateLeft(int value, int distance) {
int mask = (1 << distance) - 1;
int leftPart = (value << distance) & (~mask);
int rightPart = (value >> (32 - distance)) & (mask);
int result = leftPart | rightPart;
return result;
}
private static String printIntBitwise(int a) {
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= 32; i++) {
sb.append(Math.abs((a & (1 << (32 - i))) >> (32 - i)));
}
return sb.toString();
}
关于java - 32 位整数上的 RotateLeft 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43060297/