literature

Simple Java Programs: 1101

Deviation Actions

Omorashi's avatar
By
Published:
1.9K Views

Literature Text

class DecToBin {

    public static String number(int x) {
        String result = "";
        do {
            result = x % 2 + result; //"2" can be replaced with any other base below 10
            x = x / 2;
        } while(x != 0);
        return result;
    }

    public static void main(String[] args){
        System.out.println(number(Integer.parseInt(args[0])));
    }
}


/*If you want to transform a decimal number into a binary,
*you divide the decimal number by 2 again and again until
*only zero remains (this is what this code does).
*Like this:
*
*13/ 2 = 6 remainder 1
*6 / 2 = 3 remainder 0
*3 / 2 = 1 remainder 1
*1 / 2 = 0 remainder 1
*---> 13 is 1101 as a binary number (read from bottom to top)
*
*This works similarly with other bases.
*However, be careful when you choose a base higher than 10
*because then you will need to add more symbols (e.g. letters;
*that's the reason the hexadecimal system uses letters
*to display numbers after 9), but those are not implemented here.
*/
:bulletorange:What does this program do?
This program transforms a decimal number into its corresponding binary value.
Attention: It's not enough to run the program by executing it with "java DecToBin" (after compiling it with "javac DecToBin.java") because this program expects an argument, in this case the decimal number you want to transform. Therefore run it by typing "java DecToBin 13" or something similar.

:bulletorange:Good to know
If you want to transform a decimal number into a binary, you divide the decimal number by 2 again and again until only zero remains (this is what this code does). Like this:
13/ 2 = 6 remainder 1
6 / 2 = 3 remainder 0
3 / 2 = 1 remainder 1
1 / 2 = 0 remainder 1
---> 13 is 1101 as a binary number (read from bottom to top)
This works similarly with other bases. However, be careful when you choose a base higher than 10 because then you will need to add more symbols (e.g. letters; that's the reason the hexadecimal system uses letters to display numbers after 9), but those are not implemented here.

:bulletorange:Five easy steps to running this program
1. Get the Java Development Kit (JDK) from java.sun.com
2. Start your operating system's command line interface (like Windows PowerShell or GNU/Linux' Bash)
3. Copy the source code into an editor and save it as DecToBin.java
4. Type "javac DecToBin.java" to the command line (without quotation marks) and hit Enter to compile the program
5. Run the program with "java DecToBin 13" (or any other number) (without q.m.)
Comments3
Join the community to add your comment. Already a deviant? Log In