Main Tutorials

Java – Convert Integer to Binary

In Java, we can use Integer.toBinaryString(int) to convert an Integer to a binary string representative.

Integer.java

public final class Integer extends Number
        implements Comparable<Integer>, Constable, ConstantDesc {

          public static String toBinaryString(int i) {
            return toUnsignedString0(i, 1);
          }

          //...
}

This article will show you two methods to convert an Integer to a binary string representative.

  1. JDK Integer.toBinaryString.
  2. Old school bit masking technique.

1. Convert Int to Binary Integer.toBinaryString

1.1 This Java example tries to convert an int to a binary string representation.


  int input = 10;
  String result = Integer.toBinaryString(input);
  System.out.println(result);                   // 1010

Output

Terminal

  1010

1.2 The output of the Integer.toBinaryString is a lack of zero paddings, and we can use String.Format and replaceAll to improve or pretty print a binary string.


  int input = 10;
  String result = Integer.toBinaryString(input);
  String resultWithPadding = String.format("%32s", result).replaceAll(" ", "0");  // 32-bit Integer
  System.out.println(resultWithPadding);

Output

Terminal

  00000000000000000000000000001010

1.3 This Java example further improves the binary format with a separator.

IntToBinaryExample1.java

package com.mkyong.crypto.bytes;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class IntToBinaryExample1 {

    public static void main(String[] args) {

        int input = 10;
        String result = Integer.toBinaryString(input);
        String resultWithPadding = String.format("%32s", result).replaceAll(" ", "0");
        System.out.println(resultWithPadding);
        System.out.println(printBinary(resultWithPadding, 8, " | "));   // 00000000 | 00000000 | 00000000 | 00001010
        System.out.println(printBinary(resultWithPadding, 4, " "));     // 0000 0000 0000 0000 0000 0000 0000 1010

    }

    public static String printBinary(String binary, int blockSize, String separator) {

        List<String> result = new ArrayList<>();
        int index = 0;
        while (index < binary.length()) {
            result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
            index += blockSize;
        }

        return result.stream().collect(Collectors.joining(separator));
    }
}

Output

Terminal

00000000000000000000000000001010

00000000 | 00000000 | 00000000 | 00001010

0000 0000 0000 0000 0000 0000 0000 1010

2. Convert Int to Binary (Bit Masking)

2.1 This Java example uses bit masking to generate a binary string from an integer.


  StringBuilder result = new StringBuilder();
  for (int i = 31; i >= 0; i--) {
      int mask = 1 << i;
      result.append((number & mask) != 0 ? "1" : "0");
  }

In Bitwise AND operation, only 1 & 1 is 1.


1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

2.2 For example, int 10 a 32-bit integer, internally, computer see it as 0000 1010. The idea is we loop 32 times, and each time creates a new 32-bit int 1 << loop - 1, and performs a bitwise AND with the int 10, if the result is not equal zero, append one else append zero.

See the following patterns:


# Each loop will move the bit from the left side to the right side by 1 bit.

# loop 1
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
10000000 | 00000000 | 00000000 | 00000000     = 1 << 31
=
00000000 | 00000000 | 00000000 | 00000000     = 0 (result)

# loop 2
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
01000000 | 00000000 | 00000000 | 00000000     = 1 << 30
=
00000000 | 00000000 | 00000000 | 00000000     = 0 (result)

# fast forward...3...28

# loop 29
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
00000000 | 00000000 | 00000000 | 00001000     = 1 << 3
=
00000000 | 00000000 | 00000000 | 00001000     = 1 (result)

# loop 30
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
00000000 | 00000000 | 00000000 | 00000100     = 1 << 2
=
00000000 | 00000000 | 00000000 | 00000000     = 0 (result)

# loop 31
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
00000000 | 00000000 | 00000000 | 00000010     = 1 << 1
=
00000000 | 00000000 | 00000000 | 00000010     = 1 (result)

# loop 32
00000000 | 00000000 | 00000000 | 00001010     = 10
&                                             = Bitwise AND
00000000 | 00000000 | 00000000 | 00000001     = 1 << 0
=
00000000 | 00000000 | 00000000 | 00000000     = 0 (result)

Here’s the full example.

IntToBinaryExample2.java

package com.mkyong.crypto.bytes;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class IntToBinaryExample2 {

    public static void main(String[] args) {

        int input = 10;
        String result = convertIntToBinaryString(input);
        String resultWithPadding = String.format("%32s", result).replaceAll(" ", "0");
        System.out.println(printBinary(resultWithPadding, 8, " - "));

    }

    public static String convertIntToBinaryString(int number) {

        StringBuilder result = new StringBuilder();
        for (int i = 31; i >= 0; i--) {
            int mask = 1 << i;
            result.append((number & mask) != 0 ? "1" : "0");
        }
        return result.toString();

    }

    public static String printBinary(String binary, int blockSize, String separator) {

        List<String> result = new ArrayList<>();
        int index = 0;
        while (index < binary.length()) {
            result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
            index += blockSize;
        }

        return result.stream().collect(Collectors.joining(separator));
    }
}

Output

Terminal

  00000000 - 00000000 - 00000000 - 00001010

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments