Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of a given
- * 32-bit unsigned integer. The first and the second sequence of bits may not overlap. */
- import java.util.Scanner;
- public class BitExchange_Advanced {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a non-negative whole Number in the range [0 .. 4 294 967 295]: ");
- long number = scan.nextLong();
- System.out.print("Enter number for Start Right Bit Position: ");
- int posBitP = scan.nextInt();
- System.out.print("Enter number for Start Left Bit Position: ");
- int posBitQ = scan.nextInt();
- System.out.print("Enter number for Count of Exchanging Bits: ");
- int countK = scan.nextInt();
- scan.close();
- boolean inputIsOutRange = number < 0 || number > 4_294_967_295L
- || (countK < 0 || countK > 16) || posBitP < 0
- || (posBitP + countK - 1) > 31 || posBitQ < 0
- || (posBitQ + countK - 1) > 31;
- boolean overlapping = (posBitQ > posBitP && (posBitP + countK - 1) >= posBitQ)
- || (posBitP > posBitQ && (posBitQ + countK - 1) >= posBitP);
- if (inputIsOutRange) {
- System.out.println("Error! - Input arguments are Out of Range!!!");
- } else if (overlapping) {
- System.out.println("Error! - Your Bits Sequences Overlapping!!!");
- } else {
- long bitsMaskCount = (1L << countK) - 1;
- int bitValuePBitsSeq = (int) ((number >> posBitP) & bitsMaskCount);
- int bitValueQBitsSeq = (int) ((number >> posBitQ) & bitsMaskCount);
- long result = number;
- if (bitValuePBitsSeq != bitValueQBitsSeq) {
- result = (number ^ ((long) bitValuePBitsSeq << posBitP));
- result ^= ((long) bitValueQBitsSeq << posBitQ);
- result |= ((long) bitValueQBitsSeq << posBitP);
- result |= ((long) bitValuePBitsSeq << posBitQ);
- }
- System.out.printf("The Number after Bits Exchanges is: %d !\n", result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement