How to get 0-padded binary representation of an integer in java?

JavaBinaryString Formatting

Java Problem Overview


for example, for 1, 2, 128, 256 the output can be (16 digits):

0000000000000001
0000000000000010
0000000010000000
0000000100000000

I tried

String.format("%16s", Integer.toBinaryString(1));

it puts spaces for left-padding:

`               1'

How to put 0s for padding. I couldn't find it in Formatter. Is there another way to do it?

P.S. this post describes how to format integers with left 0-padding, but it is not for the binary representation.

Java Solutions


Solution 1 - Java

I think this is a suboptimal solution, but you could do

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')

Solution 2 - Java

There is no binary conversion built into the java.util.Formatter, I would advise you to either use String.replace to replace space character with zeros, as in:

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")

Or implement your own logic to convert integers to binary representation with added left padding somewhere along the lines given in this so. Or if you really need to pass numbers to format, you can convert your binary representation to BigInteger and then format that with leading zeros, but this is very costly at runtime, as in:

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))

Solution 3 - Java

You can use Apache Commons StringUtils. It offers methods for padding strings:

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');

Solution 4 - Java

Here a new answer for an old post.

To pad a binary value with leading zeros to a specific length, try this:

Integer.toBinaryString( (1 << len) | val ).substring( 1 )

If len = 4 and val = 1,

Integer.toBinaryString( (1 << len) | val )

returns the string "10001", then

"10001".substring( 1 )

discards the very first character. So we obtain what we want:

"0001"

If val is likely to be negative, rather try:

Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )

Solution 5 - Java

I was trying all sorts of method calls that I haven't really used before to make this work, they worked with moderate success, until I thought of something that is so simple it just might work, and it did!

I'm sure it's been thought of before, not sure if it's any good for long string of binary codes but it works fine for 16Bit strings. Hope it helps!! (Note second piece of code is improved)

String binString = Integer.toBinaryString(256);
  while (binString.length() < 16) {    //pad with 16 0's
        binString = "0" + binString;
  }

Thanks to Will on helping improve this answer to make it work with out a loop. This maybe a little clumsy but it works, please improve and comment back if you can....

binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;

Solution 6 - Java

A simpler version of user3608934's idea "This is an old trick, create a string with 16 0's then append the trimmed binary string you got ":

private String toBinaryString32(int i) {
	String binaryWithOutLeading0 = Integer.toBinaryString(i);
	return "00000000000000000000000000000000"
			.substring(binaryWithOutLeading0.length())
			+ binaryWithOutLeading0;
}

Solution 7 - Java

I do not know "right" solution but I can suggest you a fast patch.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

I have just tried it and saw that it works fine.

Solution 8 - Java

Starting with Java 11, you can use the repeat(...) method:

"0".repeat(Integer.numberOfLeadingZeros(i) - 16) + Integer.toBinaryString(i)

Or, if you need 32-bit representation of any integer:

"0".repeat(Integer.numberOfLeadingZeros(i != 0 ? i : 1)) + Integer.toBinaryString(i)

Solution 9 - Java

try...

String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));

I dont think this is the "correct" way to doing this... but it works :)

Solution 10 - Java

I would write my own util class with the method like below

public class NumberFormatUtils {

public static String longToBinString(long val) {
    char[] buffer = new char[64];
    Arrays.fill(buffer, '0');
    for (int i = 0; i < 64; ++i) {
        long mask = 1L << i;
        if ((val & mask) == mask) {
            buffer[63 - i] = '1';
        }
    }
    return new String(buffer);
}

public static void main(String... args) {
    long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
    System.out.println(value);
    System.out.println(Long.toBinaryString(value));
    System.out.println(NumberFormatUtils.longToBinString(value));
}

}

Output:

5
101
0000000000000000000000000000000000000000000000000000000000000101

The same approach could be applied to any integral types. Pay attention to the type of mask

long mask = 1L << i;

Solution 11 - Java

A naive solution that work would be

String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess

One other method would be

String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);

This will produce a 16 bit string of the integer 5

Solution 12 - Java

This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)

public class BinaryPrinter {

    public static void main(String[] args) {
        System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
        System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
        System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
    }

    public static String binaryString( final int number, final int binaryDigits ) {
        final String pattern = String.format( "%%0%dd", binaryDigits );
        final String padding = String.format( pattern, 0 );
        final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );
    
        System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );
    
        return response.substring( response.length() - binaryDigits );
    }
}

Solution 13 - Java

This method converts an int to a String, length=bits. Either padded with 0s or with the most significant bits truncated.

static String toBitString( int x, int bits ){
	String bitString = Integer.toBinaryString(x);
	int size = bitString.length();
	StringBuilder sb = new StringBuilder( bits );
	if( bits > size ){
		for( int i=0; i<bits-size; i++ )
			sb.append('0');
		sb.append( bitString );
	}else
		sb = sb.append( bitString.substring(size-bits, size) );
	
	return sb.toString();
}

Solution 14 - Java

You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.

String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));  
return  
0000000000000010  

another examples:

[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110

Solution 15 - Java

for(int i=0;i<n;i++)
{
  for(int j=str[i].length();j<4;j++)
  str[i]="0".concat(str[i]);
}

str[i].length() is length of number say 2 in binary is 01 which is length 2 change 4 to desired max length of number. This can be optimized to O(n). by using continue.

Solution 16 - Java

// Below will handle proper sizes

public static String binaryString(int i) {
    return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}

public static String binaryString(long i) {
    return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}

Solution 17 - Java

import java.util.Scanner;
public class Q3{
  public static void main(String[] args) {
  	Scanner scn=new Scanner(System.in);
  	System.out.println("Enter a number:");
  	int num=scn.nextInt();
  	int numB=Integer.parseInt(Integer.toBinaryString(num));
  	String strB=String.format("%08d",numB);//makes a 8 character code
  	if(num>=1 && num<=255){
     System.out.println(strB);
  	}else{
  		System.out.println("Number should be in range between 1 and 255");
  	}
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkhachikView Question on Stackoverflow
Solution 1 - JavaSamuel ParsonageView Answer on Stackoverflow
Solution 2 - JavaZoran RegvartView Answer on Stackoverflow
Solution 3 - JavaBunarroView Answer on Stackoverflow
Solution 4 - JavaCr4paudView Answer on Stackoverflow
Solution 5 - JavaTom SpencerView Answer on Stackoverflow
Solution 6 - JavabentoView Answer on Stackoverflow
Solution 7 - JavaAlexRView Answer on Stackoverflow
Solution 8 - JavaJohn McClaneView Answer on Stackoverflow
Solution 9 - JavaPaulView Answer on Stackoverflow
Solution 10 - JavaArseny KovalchukView Answer on Stackoverflow
Solution 11 - JavaproengView Answer on Stackoverflow
Solution 12 - Javauser3608934View Answer on Stackoverflow
Solution 13 - JavajenfaxView Answer on Stackoverflow
Solution 14 - JavaNikmassView Answer on Stackoverflow
Solution 15 - JavaJasmeet ChhabraView Answer on Stackoverflow
Solution 16 - JavaPaul WeissView Answer on Stackoverflow
Solution 17 - JavaDevesh KumarView Answer on Stackoverflow