使用Java中的前导零填充等于零(“0”)的二进制字符串 [英] Pad a binary String equal to zero ("0") with leading zeros in Java

查看:350
本文介绍了使用Java中的前导零填充等于零(“0”)的二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Integer.toBinaryString(data)

给了我一个我的数组数据的二进制字符串表示。

gives me a binary String representation of my array data.

但是我想要一种简单的方法来向它添加前导零,因为一个等于零的字节数组给我一个0字符串。

However I would like a simple way to add leading zeros to it, since a byte array equal to zero gives me a "0" String.

我想要像这样的单行:

String dataStr = Integer.toBinaryString(data).equals("0") ? String.format(format, Integer.toBinaryString(data)) : Integer.toBinaryString(data);

String.format()正确进场?如果是,我应该使用什么格式字符串?
提前致谢!

Is String.format() the correct approach? If yes, what format String should I use? Thanks in advance!

编辑:数据数组的动态长度,数字也应如此领先的零。

The data array is of dynamic length, so should the number of leading zeros.

推荐答案

对于填充,例如5个前导零,这将起作用:

For padding with, say, 5 leading zeroes, this will work:

String.format("%5s", Integer.toBinaryString(data)).replace(' ', '0');

您没有指定字符串的预期长度,在上面的示例代码中我使用了5,用适当的值替换它。

You didn't specify the expected length of the string, in the sample code above I used 5, replace it with the proper value.

编辑

我刚注意到这些评论。当然你可以动态地构建模式,但是在某些时候你必须知道最大预期大小,这取决于你的问题,你将知道如何确定值:

I just noticed the comments. Sure you can build the pattern dynamically, but at some point you have to know the maximum expected size, depending on your problem, you'll know how to determine the value:

String formatPattern = "%" + maximumExpectedSize + "s";

这篇关于使用Java中的前导零填充等于零(“0”)的二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆