I was making a program as an excercise to practice a bit. I want convert text to binary and be able to decode the binary back into text. Here's my code so far:
package text2binary;
import java.util.*;
/**
*
* @author Matt
*/
public class textToBinary {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
double text, n = 0;
String stringText, stringHelp;
stringText = "";
Scanner keyInput = new Scanner(System.in);
text = keyInput.nextDouble();
while (Math.pow(2, n) <= text){ //determines max exponent value
n++;
}
if (Math.pow(2, n) > text){ //decrement if 2^n is greater than text
n--;
}
while (n >= 0){ //This loop finds the binary representation of the decimal text/number
if (Math.pow(2, n) <= text){
text = text - (Math.pow(2, n));
stringHelp = "1";
stringText = stringText.concat(stringHelp);
n--;
}
else {
stringHelp = "0";
stringText = stringText.concat(stringHelp);
n--;
}
}
System.out.println(stringText);
}
}
Firstly is there anyway to improve this code so far that converts a number to binary? And secondly, what do you feel would be the best way of going about assigning a numerical value to a letter? Like a = 1, b = 2, c = 3 ... z = 26. Thanks for your help again. :)