/*
 * Main.java
 *
 * Created on August 21, 2006, 4:50 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Ascii2Binary;

import javax.swing.*;

/**
 *
 * @author Brandon
 */
public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Get Some ASCII Input From User
        String strAscii = JOptionPane.showInputDialog(null, "Give Me Some ASCII to Convert to Binary");

        // Make a String to Store the Output
        String strBinary = "";

        // Make A Loop to Convert Each Character to Binary
        for (int i=0; i < strAscii.length(); i++) {

            // Current Byte We Are Working On
            String curByte = "";

            // Fetch Character
            char curChar = strAscii.charAt(i);

            // Get ASCII Value of Byte (Typecasting Rules)
            int asciiValue = (int)curChar;

            // Current Bit in Current Byte
            int curBit = 0;

            while (asciiValue != 0) {
                curBit      = asciiValue % 2;
                asciiValue  = asciiValue / 2;
                curByte     = curByte + curBit;
            }

            // Does the Current Byte need Padding?
            while (curByte.length() < 8) {
                curByte = curByte + "0";
			}
            
            // Now, reverse the order of the string. ouch.
            // Luckily, I found out about StringBuilder
            StringBuilder reversedBytes = new StringBuilder(curByte);
            reversedBytes.reverse();
            curByte = reversedBytes.toString();
            
            // Add a Space for Better Output?
            curByte = curByte + " ";
                        
            // Finally, copy it into the output variable.
            strBinary = strBinary.concat(curByte);
        }

    // Show Message Dialog with Binary Output
    JOptionPane.showMessageDialog(null, strBinary); 
    }
    
}

