Friday 19 August 2016

Chapter 5 Exercise 44, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*5.44 (Computer architecture: bit-level operations) A short value is stored in 16 bits. Write a program that prompts the user to enter a short integer and displays the 16 bits for the integer. Here are sample runs:

    Enter an integer: 5
    The bits are 0000000000000101

    Enter an integer: -5
    The bits are 1111111111111011

import java.util.Scanner;
 
public class ProgrammingEx5_44 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter an integer: ");
  short n = input.nextShort();
  String s = "";
 
  short mask = 0b1; // to extract the last bit after shifting
 
  for (int i = 0; i < 16; i++) {
 
   short bit = (short) (n & mask); // extracting last bit i.e the
           // remainder of
   // division by 2
   s = bit + s;
   n = (byte) (n >> 1); // Shifting right is dividing by 2. The last
         // bit is the remainder of the next shift.
 
  }
 
  System.out.println("The bits are ");
  System.out.println(s);
 
 }
 
}

2 comments :