Advertisement
damoncard

Let's Shift Bits

Oct 30th, 2014
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.math.BigInteger; // import BigInteger method
  3. public class ShiftBits {
  4.   public static void main (String [] args) {
  5.     Scanner in = new Scanner(System.in);
  6.     System.out.print("Enter number of bits: ");
  7.     int bi = in.nextInt();
  8.     int [] a = new int [bi]; // create array to keep binary number that you have to input
  9.     for (int q = 0 ; q < a.length ; q++)
  10.     {
  11.       System.out.printf("Insert your %d position bit", q);
  12.       int d = in.nextInt();
  13.       a[q] = d; // add bit to the array
  14.     }
  15.     String b = getBi(a); // call method
  16.     printRe(b); // call method to print
  17.     System.out.println("Do you want to shift?\nIf yes and shift right say 1\nIf no say 0\nIf yes and shift left say -1"); // ask
  18.     int u = in.nextInt();
  19.     switch (u) { // use this instead of IF
  20.       case 0: System.out.print("Thank you for playing");
  21.               break; // if you forget to write this all of the case will be executed
  22.       case 1: System.out.print("What times you want to shift?: ");
  23.               int v = in.nextInt();
  24.               b = shiftR(b, v);
  25.               printRe(b);
  26.               break;
  27.       case -1: System.out.print("What times you want to shift?: ");
  28.                int k = in.nextInt();
  29.                b = shiftL(b, k);
  30.                printRe(b);
  31.                break;
  32.     }
  33.   }
  34.   public static String getBi(int[] l) {
  35.     String h = "";
  36.     for (int q = 0 ; q < l.length ; q++)
  37.     {
  38.       h = h + l[q];
  39.     }
  40.     return h;
  41.   }
  42.   public static String printRe(String n) {
  43.     System.out.printf("Your Binary is: %s\n", n);
  44.     int e = Integer.parseInt(n, 2); // change to decimal
  45.     System.out.printf("Your Decimal value is: %d\n", e);
  46.     String r = new BigInteger(n, 2).toString(16).toUpperCase(); // change to Hexadecimal and change to uppercase
  47.     System.out.printf("Your Hexacimal value is: %s\n", r);
  48.     return n;
  49.   }
  50.   public static String shiftR(String i, int d) {
  51.     String x = i;
  52.     for (int q = 0 ; q < d ; q++)
  53.     {
  54.       x = x + 0;
  55.     }
  56.     return x;
  57.   }
  58.   public static String shiftL(String i, int d) {
  59.     String z = i;
  60.     for (int q = 0 ; q < d ; q++)
  61.     {
  62.       z = 0 + z;
  63.     }
  64.     return z;
  65.   }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement