Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write your code in the file Convert.java. Your code should go into a method with

ID: 3804837 • Letter: W

Question

Write your code in the file Convert.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method: public static int convert (String binaryString, boolean signBit){} In the beginning of the class you were taught an algorithm for converting binary strings to their decimal integer equivelant. The sign bit is as follows: true for signed integer, false for unsigned integer. For a signed integer, the most significant bit is the leftmost bit, with 0 for positive and 1 for negative. For example, given the following input denoting an unsigned integer: 10, false After applying the algorithm, this string is converted into. 2 And given the following input denoting a signed integer: 01, true After applying the algorithm, this string is converted into. 1

Explanation / Answer


// Convert.java
import java.io.*;
class Convert
{
   public static double convert(String binaryString, boolean signBit)
   {
      double decimalValue = 0;

      if(signBit == true)
      {
          int power = 0;
          for (int i = binaryString.length()-1 ; i >= 1; i--)
          {
              char c = binaryString.charAt(i);
              decimalValue = decimalValue + Character.getNumericValue(c)*Math.pow(2,power);  
              power++;
          }

          if(binaryString.charAt(0) == '1')
          decimalValue = -1*decimalValue;
      }

      else
      {
          int power = 0;
          for (int i = binaryString.length()-1 ; i >= 0; i--)
          {
              char c = binaryString.charAt(i);
              decimalValue = decimalValue + Character.getNumericValue(c)*Math.pow(2,power);
              power++;  
          }
      }

      return decimalValue;

   }
   public static void main(String args[])throws IOException
   {
       System.out.println(convert("10",false));
       //output: 2
       System.out.println(convert("01",true));
       //output: 1
       System.out.println(convert("111",true));
       //output: -3
   }
}