Friday, 15 February 2013

BINARY CONVERTER


import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
//Convert numbers in base 10 to user specified base or negative base 2
public class Binary
{
     public static void main ( String [] args )
     {
         Scanner input = new Scanner( System.in );

         System.out.print("Enter Number in base 10: ");
         int base10 = input.nextInt();
       
         System.out.print("Enter Number in required base: ");
         int base = input.nextInt();

         ArrayList<Integer> result = new ArrayList<Integer>();//Create dynamic array
         
         //Convert from positive base 10 to specified base
         if (base10 > 0) {
           while ( base10 != 0 ) {
              result.add(base10%base);
               base10 = base10/base;
         }
          Collections.reverse(result);//reverse the order of the array

          System.out.println( "\nResult in Binary is " + result +"." );
           }
          //Convert negative base 10 digit to base 2
          else {
             base10 = (base10 + 1) * -1;
             while ((base10 != 0) && (base == 2)) {
              if (base10%base == 0) result.add(1);
               else if (base10%base == 1)
                result.add(0);                
                  base10 = base10/base;
            }
          Collections.reverse(result);//reverse the order of the array

          System.out.println( "\nResult in Binary is " + result +"." );
          }
     }
}
/*The program works perfectly for unsigned integers
   however signed integers seem to be a problem. In
   all honesty, i can't be asked to create a proper functioning
   logic for signed integers. It's not like most of you view this
   blog anyway lol.*/

       

No comments:

Post a Comment