Skip to content

Instantly share code, notes, and snippets.

@mjhale
Created August 3, 2012 00:01
Show Gist options
  • Save mjhale/3242311 to your computer and use it in GitHub Desktop.
Save mjhale/3242311 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.util.Arrays;
public class BinaryConverter {
public static String userOption;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
userOption = getInput(keyboard);
while (!userOption.equalsIgnoreCase("QUIT")) {
if (userOption.equalsIgnoreCase("BD")) {
System.out.print("Please enter a binary string: ");
String binaryNumber = keyboard.next();
System.out.println(binaryToDecimal(binaryNumber));
} else if (userOption.equalsIgnoreCase("DB")) {
System.out.print("Please enter a number: ");
int number = keyboard.nextInt();
System.out.println(Arrays.toString(decimalToBinary(number)));
} else {
System.out.println("Invalid Command.");
}
userOption = getInput(keyboard);
}
}
// ############################################
// ############## Get User Input ##############
// ############################################
public static String getInput(Scanner keyboard) {
System.out.print("Please enter an option: ");
return keyboard.next();
}
// ############################################
// ############# Binary to Decimal ############
// ############################################
public static int binaryToDecimal(String binaryNumber) {
int decimal = 0;
for (int i = 0; i < binaryNumber.length(); i++) {
decimal *= 2;
decimal += binaryNumber.charAt(i) - '0';
}
return decimal;
}
// ############################################
// ############# Decimal to Binary ############
// ############################################
// Let's get the length of an array
public static int getLength(int number) {
int length = 0;
while (number >= 1) {
// Divide number by two until the number
// is less than 1
number >>>= 1;
length++;
}
return length;
}
// Fill in the array
public static int[] decimalToBinary(int number) {
// Make an array with the appropriate number of (empty) values
// For 4:
// [0, 0, 0]
int arrayLength = getLength(number);
int[] numArray = new int[arrayLength];
int i = numArray.length - 1;
while (number >= 1) {
// Retains number 1 & 1
// 0011
// 0110
// ----
// 0010 <-- result
// http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
numArray[i--] = number & 1;
number >>>= 1;
}
return numArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment