You are on page 1of 6

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.

Method 1 of parity check:

Method 2 of parity check:


3. Write a program to swap the ith bit with jth bit of a number using bit wise
operations.
4. Write a program that takes a 64-bit word and returns the 64-bit word consisting
of the bits of the input word in reverse order. For example, if the input is
alternating 1s and 0s, i.e., (1010...10), the output should be alternating 0s and 1s,
i.e., (0101...01).
5. Write a java program to compute x × y without arithmetic 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

You might also like