按位乘法并在 Java 中添加
我有同时进行乘法和加法的方法,但我只是无法弄清楚它们。它们都来自外部网站,而不是我自己的网站:
public static void bitwiseMultiply(int n1, int n2) {
int a = n1, b = n2, result=0;
while (b != 0) // Iterate the loop till b==0
{
if ((b & 01) != 0) // Logical ANDing of the value of b with 01
{
result = result + a; // Update the result with the new value of a.
}
a <<= 1; // Left shifting the value contained in 'a' by 1.
b >>= 1; // Right shifting the value contained in 'b' by 1.
}
System.out.println(result);
}
public static void bitwiseAdd(int n1, int n2) {
int x = n1, y = n2;
int xor, and, temp;
and = x & y;
xor = x ^ y;
while (and != 0) {
and <<= 1;
temp = xor ^ and;
and &= xor;
xor = temp;
}
System.out.println(xor);
}
我尝试进行分步调试,但它对我来说并没有多大意义,尽管它有效。
我可能正在寻找的是尝试并理解它是如何工作的(也许是数学基础?)。
编辑:这不是家庭作业,我只是试图学习Java中的按位操作。