Shifting Bits Solution
The programming task was to write an interactive bit shifter. Given a menu of three options the user should be able to shift the bits of a number either to the right or left.
When the binary number of 1011 is subjected to one bit shift to the right followed by four bit shifts to the left, the program should display:
01010000 = 80
Here's my version of the program:
import java.util.Scanner; public class BinaryShift { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter in binary number (e.g., 1011): "); String binaryText = input.nextLine(); //get the denary value of //the binary number long binaryNumber = Long.parseLong(binaryText, 2); int menuChoice; do { //for formatting purposes change the //number into a binary string then back //to a long value Long binaryDisplay = Long.parseLong(Long.toBinaryString(binaryNumber)); //now we can format for leading zeros //%08d says pad the number with leading zeros //until the length of the number is 8 digits System.out.printf("%08d = %d%n",binaryDisplay, binaryNumber); System.out.println("1. Shift bits to the right"); System.out.println("2. Shift bits to the left"); System.out.println("3. Stop shifting"); System.out.println("Enter choice:"); menuChoice = input.nextInt(); if (menuChoice == 1) { binaryNumber = binaryNumber >> 1; } else if (menuChoice == 2) { binaryNumber = binaryNumber << 1; } }while (menuChoice != 3); } }
SHARE