Monday, April 2, 2012

Convert An Integer To Binary Array In Java

Integer is one of the built-in classes in the Java programming language. An Integer object stores a value that can be converted to other bases such as decimal (base 10) or binary (base 2) for further processing, display or storage. You can convert a Java Integer into an array of ones and zeroes, corresponding to the binary representation of the Integer.


Instructions


1. Include the following line at the beginning of your Java code:








import java.lang.Integer;


2. Create an Array with as many elements as there are binary digits in the representation of the Integer in question:


int nDigits = Math.ceil(log(0.0+myInteger));


Integer binaryRepresentation[nDigits];


Replace "myInteger" with the Integer you want to convert to binary.


3. Convert the Integer to binary by iterating over its digits one by one, starting with the least significant digit, as in the following sample code:


int remainder = myInteger;


for (int i=0; i

binaryRepresentation[i] = remainder % 2;


remainder = remainder / 2;


}


After executing this code, "binaryRepresentation[0]" will contain the least significant bit in the binary representation of "myInteger," and so on until "binaryRepresentation[nDigits-1]" that will contain the most significant bit.

Tags: binary representation, Convert Integer, least significant, remainder remainder, representation Integer