1. Computing & Technology

Discuss in my forum

Shifting Bits

By , About.com Guide

Level: Beginner

Focus: Binary Numbers, Bitwise Operators, Formatting Numbers

Shifting Bits Question

This programming exercise is a test of your skills at formatting binary numbers 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 the variable bitShift is now 8.

The task is 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 number in denary and its 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).

To test the program, use the binary number 1011 as the starting value and perform one bit shift to the right followed by four bit shifts to the left. What is the final denary value and bit pattern?

To get the most out of this question try and figure out the answer before coming back to read the solution on the next page.

©2012 About.com. All rights reserved.

A part of The New York Times Company.