I did research about binary counting, and wanted to make an application in Java that converts a string to binary code:
/**
* This class converts strings by looping through the characters, gets the
* decimal code for each, then divides the number by 2 untill the quotient is 0
*
* @author Mr Pro Pop
*
*/
public class Binary {
/**
* This function takes a string as a parameter and converts it to binary code
*
* @param string The string to be converted to binary code
* @return The binary code of the input string
*/
public String getBinaryCode(String string) {
if (string.length() == 0)
return null;
char[] characters = string.toCharArray();
StringBuilder result = new StringBuilder();
int number = 0;
for (int i = 0; i < characters.length; i++) {
number = getDecimal(characters[i]);
for (int j = 0; j < 8; j++) {
if (number % 2 == 0) {
result.insert(0, 0);
} else {
result.insert(0, 1);
}
number = (int) (number / 2);
}
result.append(" ");
}
return result.toString();
}
/**
* This function gets the decimal number of a character
*
* @param character The character that we want the decimal value of
* @return The decimal of the character from the ascii table
*/
public int getDecimal(char character) {
for (int i = 0; i <= 255; i++) {
if (character == (char) i) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
String string = "a";
Binary b = new Binary();
System.out.println("Binary code for" + string + " is " + b.getBinaryCode(string));
}
}
Output:
Binary code for a is 01100001
Here it works well, however, spacing doesn't work. I do acknowledge that I could simply code this in a different easier method by Integer.toBinaryString(character[i])
but tried doing it my way to learn and especially with this method.
Any improvements I could do or anything to pay attention for?