How to Convert an Integer to Binary Array in Java

Written by jonah quant
  • Share
  • Tweet
  • Share
  • Email

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.

Skill level:
Easy

Other People Are Reading

Instructions

  1. 1

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

    import java.lang.Integer;

  2. 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 binary Representation[nDigits];

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

  3. 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 = my Integer;

    for (int i=0; i<nDigits; I++) {

    binary Representation[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.

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.