import java.util.*;
public class BinaryConverter {

	public static void main(String[] args) {

		int [] powersOfTwo = new int[8];
		Scanner scan = new Scanner(System.in);
		String binaryNum;
		int total = 0;

		initialize(powersOfTwo);	// call "helper" method below
		
		//ask the user for a 8-bit binary number until the user gets it right
		do {
			System.out.println("Please input a 8 digit string of 0s and 1s");
			binaryNum = scan.nextLine();
		} while (binaryNum.length() != 8);
		
		//compute the value of the binary number 
		for(int j = 0; j < 8; j++)
		{
			//you only need to add to the total if there is a 1
			if (binaryNum.charAt(j) == '1')   // NOTE: Use single quotes!
				total += powersOfTwo[j]; 
		}
		
		System.out.println("the value of the binary number " + binaryNum + " is " + total);
		
		// ADDITIONAL EXERCISE
		// compute the value of the signed binary number if negative

		total = 0;
		if (binaryNum.charAt(0) == '1')		// leftmost bit is 1 means negative
		{
			// compute 1's complement by flipping bits (or adding when you see 0s instead of 1s)
			for(int j = 1; j < 8; j++) {
				//you only need to add to the total if there is a 0
				if (binaryNum.charAt(j) == '0')   // NOTE: Use single quotes!
					total += powersOfTwo[j]; 
			}
			total += 1;	// add 1 to make 2's complement
			total *= -1;	// make negative
		}
		else {  // same as problem #3 except no need to use index 0 of powersOfTwo array since we know it stores a 0
	                for(int j = 1; j < 8; j++ {        
 	                       if (binaryNum.charAt(j) == '1') 
	                                total += powersOfTwo[j];
        	        }
		}		
		System.out.println("The signed value of the binary number " + binaryNum + " is " + total);
	}
	
	public static void initialize(int[] powersOfTwo) {
		//initialize the array with the powers of 2
		powersOfTwo[7] = 1;	
		for (int i = 6; i >= 0; i--) {
			powersOfTwo[i] = 2 * powersOfTwo[i+1];
		}
	}		

}
