Created
May 4, 2014 00:43
-
-
Save wffurr/8b50e5028349d4a59196 to your computer and use it in GitHub Desktop.
Convert String decimal to String binary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DecimalToBinary { | |
/** Given a decimal number as a string, returns the binary representation as a string or "ERROR" if it can't be converted to binary */ | |
public static String decimalToBinary(String decimal) { | |
int dec = 0; | |
try { | |
dec = Integer.parseInt(decimal); | |
} catch(NumberFormatException ex) { | |
return "ERROR"; | |
} | |
if(dec == 0) return "0"; | |
StringBuilder result = new StringBuilder(); | |
while(dec != 0) { | |
result.insert(0, (dec & 1) == 1 ? "1" : "0"); | |
dec >>= 1; | |
} | |
return result.toString(); | |
} | |
public static void runTest(String decimal, String binary) { | |
String result = decimalToBinary(decimal); | |
if(!binary.equals(result)) { | |
System.out.println("For " + decimal + " expected " + binary + " got " + result); | |
} | |
} | |
public static void main(String[] args) { | |
runTest("0", "0"); | |
runTest("1", "1"); | |
runTest("2", "10"); | |
runTest("33", "100001"); | |
runTest("1.1", "ERROR"); | |
runTest("3000000000000", "ERROR"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment