Advertisement
dimipan80

Bit Exchange (Advanced)

Aug 5th, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. /* Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …, q+k-1} of a given
  2.  * 32-bit unsigned integer. The first and the second sequence of bits may not overlap. */
  3.  
  4. import java.util.Scanner;
  5.  
  6. public class BitExchange_Advanced {
  7.  
  8.     public static void main(String[] args) {
  9.         // TODO Auto-generated method stub
  10.         Scanner scan = new Scanner(System.in);
  11.         System.out.print("Enter a non-negative whole Number in the range [0 .. 4 294 967 295]: ");
  12.         long number = scan.nextLong();
  13.         System.out.print("Enter number for Start Right Bit Position: ");
  14.         int posBitP = scan.nextInt();
  15.         System.out.print("Enter number for Start Left Bit Position: ");
  16.         int posBitQ = scan.nextInt();
  17.         System.out.print("Enter number for Count of Exchanging Bits: ");
  18.         int countK = scan.nextInt();
  19.         scan.close();
  20.  
  21.         boolean inputIsOutRange = number < 0 || number > 4_294_967_295L
  22.                 || (countK < 0 || countK > 16) || posBitP < 0
  23.                 || (posBitP + countK - 1) > 31 || posBitQ < 0
  24.                 || (posBitQ + countK - 1) > 31;
  25.  
  26.         boolean overlapping = (posBitQ > posBitP && (posBitP + countK - 1) >= posBitQ)
  27.                 || (posBitP > posBitQ && (posBitQ + countK - 1) >= posBitP);
  28.  
  29.         if (inputIsOutRange) {
  30.             System.out.println("Error! - Input arguments are Out of Range!!!");
  31.         } else if (overlapping) {
  32.             System.out.println("Error! - Your Bits Sequences Overlapping!!!");
  33.         } else {
  34.             long bitsMaskCount = (1L << countK) - 1;
  35.  
  36.             int bitValuePBitsSeq = (int) ((number >> posBitP) & bitsMaskCount);
  37.             int bitValueQBitsSeq = (int) ((number >> posBitQ) & bitsMaskCount);
  38.  
  39.             long result = number;
  40.             if (bitValuePBitsSeq != bitValueQBitsSeq) {
  41.                 result = (number ^ ((long) bitValuePBitsSeq << posBitP));
  42.                 result ^= ((long) bitValueQBitsSeq << posBitQ);
  43.  
  44.                 result |= ((long) bitValueQBitsSeq << posBitP);
  45.                 result |= ((long) bitValuePBitsSeq << posBitQ);
  46.             }
  47.  
  48.             System.out.printf("The Number after Bits Exchanges is: %d !\n", result);
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement