Bits Practice

This program contains a method that can COUNT the number of 1-BITS in a byte.  This is an essential method for creating a Parity-Check.

(1) Copy the program, run it, and test it.  For example, can it correctly count the number of bits in the byte:  11111111 bin ?

(2) Add a new method called parity(byte b), that accepts a byte as an input parameter and returns either 1 or 0, depending on the number of 1-bits in the byte.

(3) Standard ASCII codes use only 7 bits, so the letters stop at code 127.  Write a method called Pascii that accepts a char as an input parameter, changes it to a byte, counts the number of 1-bits, determines the correct parity-bit, and ATTACHES this bit to the FRONT of the byte as the MSB (most significant bit).  Use ODD-PARITY.  For example:

'A' -->  65 -->  0100 0001  -->  parity bit = 1  -->  1 100 0001

Return a BYTE as a result, not a char.  Notice that the value might be negative if you print it out.

(4) A String consists of many bytes.  Thus it is appropriate to compute a CHECK-SUM for a String.  Create a method that accepts a String as an input parameter and then ADDS UP all the ASCII codes for the characters in the String.  It should return the Least Significant Byte (last byte) of this sum.  For example:

"ABCDE" -->  65+66+67+68+69 = 335  -->  14F hex -->  4F hex --> 79 dec


public class Bits extends IBIO
{
   public static void main(String[] args)
   {
      new Bits();
   }
   
   public Bits()
   {
      byte b = inputByte("Type a BYTE:");
      output(b);
    
      output("Number of 1 bits = " + countBits(b) );  
   }
      
   public int countBits(byte b)
   {
      int count = 0;
      int power = 1;
      while (power <= 128)
      {
         if ( (b & power) != 0)
         {  count = count + 1;  }
         
         power = power * 2;
      }
      return count;
   }
}