Reputation: 43
int product = 0;
String num1 = "11100001";
String num2 = "10110001";
int multiplicand = Integer.parseInt(num1);
int multiplier = Integer.parseInt(num2);
for(int i=7; i>=0; i--) {
if((multiplier & 01) != 0) {
product=product+multiplicand;
}
multiplicand <<=1;
multiplier >>=1;
}
System.out.println((product));
This is the code for binary multiplication. It has been asked about many times but I still have following confusion about this question:
After the shifting operation,the binary result does not remain binary anymore. At the end the product variable is not binary. How do I don't let shifting affect the final result, so that the product is in binary? (In this specific example, the answer is 2115700113 which is clearly not a binary number.
What does 01 mean in (multiplier & 01)?
Thanks for answer in advance.
Upvotes: 0
Views: 288
Reputation: 7620
Just add this as a last statement:
System.out.println(Integer.toBinaryString(product));
To see the binary version of your product.
Java prints out the numbers using decimal base numbers, since human is the master. Internally in the memory, or CPU registry everything is binary.
Upvotes: 0
Reputation: 401
Try Integer.parseInt("100101", 2);
This will parse the integer as a binary number.
Upvotes: 1