Thursday, April 2, 2015

Addendum To Binary

But wait! There's more...

Referring to the previous post on binary which you can check out here, there's an easy way to convert from decimal to binary, but it does require some math. We will explain this, then show its implementation in a computer program.

When given an integer in decimal format, in order to convert it to binary, you can use the method of dividing by 2's. This means you take your decimal number, and to start, divide it by 2. If there is a remainder (it doesn't matter what that remainder is), then you would represent that bit with a 1. If it divides cleanly into 2, then you represent that bit with a 0. You then take the floor of the answer you got by the division (round down to the nearest integer), and perform the division by 2 again, and follow the same rules until you reach 0 as your answer. You then would read the binary representation of the number from last representation to first representation, as the first division you performed was actually the least significant bit. The steps are written below, as well as an example.

1. start with an integer to be converted to binary
2. integer / 2
3. if the remainder is 0, represent bit with a 1
4. otherwise, represent the bit with a 0
5. take the floor of the answer found in step 2
6. perform step 2-5 until you reach 0
7. read the bits from last to first


https://www.cs.uaf.edu/2000/fall/cs301/notes/Chapter3/img36.gif
A representation of decimal 95 in binary, which reads 1011111.

And finally, below is some Java code to represent this formula. The comments should sort out the rest. Hope you enjoyed!


    /**
     * Returns a String containing the binary equivalent of an integer.
     * Note that this method calculates the bits, then reverses them, as the
     * formula that is utilized creates the LSB (least significant bit) first.
     * This also means that any set of bits returned will be preceeded by a 1.
     * @param x     The integer to be converted to binary.
     * @return      The reversed toString of the created StringBuilder, which
     *              holds all of the bits needed to represent the integer.
     */
    private static String convertToBi(int x) {
        StringBuilder sb = new StringBuilder();
        
        //for loop starts at the inputted integer parameter and
        //iteratively decrements loop variable by a division of 2
        for(int i = x; i != 0; i = i / 2) {
            if(i % 2 == 0)      //if the remainder is 0 when dividing by 2,
                sb.append(0);   //represent that bit with a 0
            else
                sb.append(1);   //otherwise, represent that bit with a 1
        }
        return sb.reverse().toString(); //essentially, read the bits MSB -> LSB
    }