Friday 24 January 2020

Java: Pad 0’s to binary representation of integer

Step 1: Convert integer to binary using ‘Integer.toBinaryString’ method.

Step 2: Pad zeros to string using String.format method.

String getPaddedBinaryString(int number, int binaryStrLength) {
         String binary = Integer.toBinaryString(number);
         return String.format("%" + binaryStrLength + "s", binary).replace(' ', '0');
}

App.java
package com.sample.app;

public class App {

 private static String getPaddedBinaryString(int number, int binaryStrLength) {
  String binary = Integer.toBinaryString(number);
  return String.format("%" + binaryStrLength + "s", binary).replace(' ', '0');
 }

 public static void main(String[] args) {
  int num = 9;

  String paddedString = getPaddedBinaryString(num, 16);

  System.out.println(paddedString);

 }

}

Output
0000000000001001



You may like

No comments:

Post a Comment