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

发布于 2024-10-07 05:17:10 字数 636 浏览 3 评论 0原文

例如,对于 1, 2, 128, 256 输出可以是(16 位数字):

0000000000000001
0000000000000010
0000000010000000
0000000100000000

我尝试

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

为左侧填充添加空格:

`               1'

How to put 0s for填充。我在 Formatter< 中找不到它/a>.还有其他方法吗?

PS这篇文章描述了如何使用左0填充格式化整数,但它不适用于二进制表示。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

暗恋未遂 2024-10-14 05:17:11
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");
    }
  }
}
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");
    }
  }
}
巾帼英雄 2024-10-14 05:17:10

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

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

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

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
初见终念 2024-10-14 05:17:10

java.util.Formatter 中没有内置二进制转换,我建议您使用 String.replace 将空格字符替换为零,如下所示:

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

或者实现您自己的逻辑,将整数转换为二进制表示形式,并在某处添加左侧填充沿着this中给出的路线。
或者,如果您确实需要传递数字进行格式化,您可以将二进制表示形式转换为 BigInteger,然后使用前导零对其进行格式化,但这在运行时非常昂贵,如下所示:

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

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)))
很糊涂小朋友 2024-10-14 05:17:10

这是旧帖子的新答案。

要将带有前导零的二进制值填充到特定长度,请尝试以下操作:

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

如果 len = 4val = 1

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

则返回字符串 "10001",然后

"10001".substring( 1 )

丢弃第一个字符。所以我们得到了我们想要的:

"0001"

如果 val 很可能为负,那么尝试:

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

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 )
十雾 2024-10-14 05:17:10

您可以使用 Apache Commons StringUtils 。它提供了填充字符串的方法:

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

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

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
不羁少年 2024-10-14 05:17:10

我尝试了以前从未真正使用过的各种方法调用来完成这项工作,它们取得了一定的成功,直到我想到了一些非常简单的方法,它可能会起作用,而且确实如此!

我确信以前已经考虑过它,不确定它对于长字符串二进制代码是否有任何好处,但对于 16 位字符串它工作得很好。希望有帮助!! (注意第二段代码已得到改进)

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

感谢威尔帮助改进了这个答案,使其无需循环即可工作。
这可能有点笨拙,但它有效,如果可以的话请改进并发表评论......

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;

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;
心病无药医 2024-10-14 05:17:10

user3608934 的想法的更简单版本“这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加您得到的修剪后的二进制字符串”:

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

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;
}
少跟Wǒ拽 2024-10-14 05:17:10

从 Java 11 开始,您可以使用 repeat(...) 方法:

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

或者,如果您需要任何整数的 32 位表示:

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

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)
清醇 2024-10-14 05:17:10

我不知道“正确”的解决方案,但我可以建议您一个快速补丁。

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

我刚刚尝试过,发现效果很好。

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.

放血 2024-10-14 05:17:10

尝试...

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

我不认为这是执行此操作的“正确”方法...但它有效:)

try...

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

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

怪我鬧 2024-10-14 05:17:10

我将使用如下方法编写自己的 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));
}

}

输出:

5
101
0000000000000000000000000000000000000000000000000000000000000101

相同的方法可以应用于任何整数类型。注意mask的类型

long mask = 1L <<我;

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;

纵山崖 2024-10-14 05:17:10

一个可行的简单解决方案是

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

另一种方法是

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

这将产生整数 5 的 16 位字符串

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

风轻花落早 2024-10-14 05:17:10

您可以使用 lib https://github.com/kssource/BitSequence。它接受一个数字并返回经过填充和/或分组的二进制字符串。

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

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
如梦亦如幻 2024-10-14 05:17:10

// 下面将处理适当的尺寸

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

// 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');
}
柠北森屋 2024-10-14 05:17:10

这是一个老技巧,创建一个包含 16 个 0 的字符串,然后附加从 String.format("%s", Integer.toBinaryString(1)) 获得的修剪后的二进制字符串,并使用最右边的 16 个字符,去掉任何前导0 的。更好的是,创建一个函数,让您指定所需的二进制字符串的长度。当然,可能还有无数其他方法可以完成此任务,包括库,但我添加这篇文章是为了帮助朋友:)

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

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 );
    }
}
风吹雪碎 2024-10-14 05:17:10

该方法将 int 转换为 String,长度=位。用 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();
}

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();
}
小草泠泠 2024-10-14 05:17:10
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() 是数字的长度,比如二进制中的 2 是 01,即长度 2
将 4 更改为所需的最大数字长度。这可以优化为 O(n)。
通过使用继续。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文