Java: Convert an Integer to a String of Binary ASCII Characters

Date: 2014-02-05 |

**Problem: **Create a method that converts an integer to a String of binary ASCII characters without using built-in library commands.  Use only the number of bits needed to contain the integer (i.e. no leading zeros).

My code is below:

(https://gist.github.com/SIRHAMY/8838367)

I started off by setting the result variable (the variable to be returned) to 0 in order to cover the edge case in which the given integer was 0 and the while loop/for loop weren’t entered.

The first while loop sets out to determine the length of binary string needed to encompass the integer.  Once the greatest place with a 1 is found (by continually raising the scalar by a multiple of two), we break out of the while loop with a variable called placeHolder containing the number of bits in the binary string.

The for loop then goes about filling in the rest of the bits with the appropriate bit value using a similar method.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.