Java

  1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy

Paul's Java Blog

By Paul Leahy, About.com Guide to Java

Answer to Monday's Bitwise Question

Sunday January 4, 2009

Monday's programming question was to write an interactive bit shifter. Given a menu of three options the user should have been 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 have displayed:

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);
  }
}

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss

Community Forum

Explore Java

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Java

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.