How to Convert an Integer to Binary Array in Java

Save

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.

  • Include the following line at the beginning of your Java code:

    import java.lang.Integer;

  • 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.

  • 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<nDigits; 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.

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!