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

By Paul Leahy, About.com Guide to Java

Monday's Programming Question

Monday December 29, 2008

This week the programming question is a test of your skills at formatting output combined with using bitwise operators. Bitwise operators interact directly with the underlying bits of a number. For example, the number 16 is the binary equivalent of 10000. The binary shift operators can be used to shift the bit pattern of a number either to the right (i.e., use the >> operator) or to the left (i.e., use the << operator). So,

int bitShift = 16;
bitShift = bitShift >> 1;

will shift the binary pattern 10000 of 16 one place to the right. The new bit pattern 1000 means the value of variable bitShift is now 8.

The Java program to write is an interactive bit shifter. The program must accept a binary number written as a String. It should then display the value of the binary number in denary and it's binary pattern, followed by a menu of options. The menu should allow the user to:

  1. Shift bits to the right
  2. Shift bits to the left
  3. Stop shifting

If the user picks option 1 or 2 the corresponding bit shift should occur on the number. The new value and bit pattern should be displayed to the user followed by the menu. Option 3 should stop the program. To make things a little more interesting the bit pattern must be displayed as an 8 bit number (i.e., the binary number 101 should be formatted to have 5 leading zeros 00000101).

If you enter the binary number 1011 into your program and perform one bit shift to the right followed by four bit shifts to the left what is the denary value and bit pattern?

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

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

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

  1. Home
  2. Computing & Technology
  3. Java

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

All rights reserved.