Professional Documents
Culture Documents
Solution of Problems On Bitwise Operations
Solution of Problems On Bitwise Operations
1. Write a Java program to count the number of bits that are set to 1 in an integer
using operators.
2. The parity of a binary word is 1 if the number of 1s in the word is odd; otherwise,
it is 0. Write a Java program to count the parity of an integer number using
bitwise operators.
Solution:
Y=1101 =13
×
X=1001 =9
1101
+ 0000
0000
1101
1110101 =117
6. Write a java program to compute x/y using addition, subtraction, and shifting
operators.
Solution:
Step 1: Compute the largest k such that 2ky < x
Step 2: Subtract 2ky from x
Step 3: Add 2ky to the quotient
7. Write a program to find xy without using math libraries and exponent operators.
Shifting operator should be used. Ensure that the program handles both positive
and negative exponents.
Solution:
Generalizing, if the least significant bit of y is 0, the result is (Xy/2)2; otherwise, it is X ×
(Xy/2)2. This gives us a recursive algorithm for computing Xy when y is non-negative.
Example: Find x6 and x7. (Xy)
X6 = (X6/2)2= (X3)2, where y=110, LSB is 0 (even)
X7 = X × (X6/2)2 = X ×(X3)2 , where y=111, LSB is 1 (odd)
• The only change when y is negative is replacing x by 1/x and y by −y.
Solution: Compute xy without Arithmeti