简体   繁体   中英

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

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 0 s for padding. I couldn't find it in Formatter . Is there another way to do it?

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

我认为这是一个次优的解决方案,但你可以这样做

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

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)))

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

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

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 )

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;

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;
}

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.

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)

try...

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

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

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

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 );
    }
}

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;

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();
}

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

// 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');
}
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");
    }
  }
}
String binaryString = Integer.toBinaryString(2);
while (binaryString.length() < 32) binaryString = "0" + binaryString;

Since Java's integers are always 32-bit you can just prepend zeros to the binary string until its length is 32 characters (ie. 32 binary digits)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM