Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Converting Text to Binary

807601Jun 7 2008 — edited Jun 7 2008
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. :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 5 2008
Added on Jun 7 2008
1 comment
272 views