简体   繁体   English

如何在java中获得整数的0填充二进制表示?

[英]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):例如,对于1, 2, 128, 256输出可以是(16 位):

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.如何将0 s 用于填充。 I couldn't find it in Formatter .我在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. PS 这篇文章描述了如何用左 0 填充来格式化整数,但它不是用于二进制表示。

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

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: java.util.Formatter 中没有内置二进制转换,我建议您使用 String.replace 用零替换空格字符,如下所示:

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:或者,如果您确实需要将数字传递给格式,则可以将二进制表示形式转换为 BigInteger,然后使用前导零对其进行格式化,但这在运行时非常昂贵,例如:

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

You can use Apache Commons StringUtils .您可以使用 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 ,如果len = 4val = 1

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

returns the string "10001" , then返回字符串"10001" ,然后

"10001".substring( 1 )

discards the very first character.丢弃第一个字符。 So we obtain what we want:所以我们得到了我们想要的:

"0001"

If val is likely to be negative, rather try:如果val可能是负数,请尝试:

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.我确定之前已经考虑过它,不确定它对长串二进制代码是否有好处,但它适用于 16Bit 字符串。 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.感谢 Will 帮助改进这个答案,使其在没有循环的情况下工作。 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 ": user3608934 想法的更简单版本“这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加您得到的修剪后的二进制字符串”:

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:从 Java 11 开始,您可以使用repeat(...)方法:

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

Or, if you need 32-bit representation of any integer:或者,如果您需要任何整数的 32 位表示:

"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这将产生一个整数 5 的 16 位字符串

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.这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加从 String.format("%s", Integer.toBinaryString(1)) 获得的修剪后的二进制字符串,并使用最右边的 16 个字符,去掉任何前导0 的。 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我会用下面的方法编写我自己的 util 类

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.此方法将 int 转换为 String,length=bits。 Either padded with 0s or with the most significant bits truncated.用 0 填充或截断最高有效位。

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 .您可以使用 lib https://github.com/kssource/BitSequence It accept a number and return bynary string, padded and/or grouped.它接受一个数字并返回 bynary 字符串,填充和/或分组。

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. str[i].length()是数字的长度,例如二进制中的 2 是 01,即长度 2 将 4 更改为所需的最大数字长度。 This can be optimized to O(n).这可以优化为 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) 由于Java的整数始终为32位,因此您可以在二进制字符串前加零,直到其长度为32个字符(即32个二进制数字)为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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