简体   繁体   English

在Java中使用零填充左填充整数(非小数格式)

[英]Left padding integers (non-decimal format) with zeros in Java

The question has been answered for integers printed in decimal format , but I'm looking for an elegant way to do the same with integers in non-decimal format (like binary, octal, hex). 已经回答了以十进制格式打印的整数的问题,但我正在寻找一种优雅的方法来对非十进制格式的整数(如二进制,八进制,十六进制)执行相同的操作。

Creation of such Strings is easy: 创建这样的字符串很容易:

String intAsString = Integer.toString(12345, 8);

would create a String with the octal represenation of the integer value 12345. But how to format it so that the String has like 10 digits, apart from calculating the number of zeros needed and assembling a new String 'by hand'. 将创建一个具有整数值12345的八进制表示的字符串。但是如何格式化它以使字符串具有10个数字,除了计算所需的零的数量和手动组装新的字符串。

A typical use case would be creating binary numbers with a fixed number of bits (like 16, 32, ...) where one would like to have all digits including leading zeros. 一个典型的用例是创建具有固定位数(如16,32,...)的二进制数,其中一个人想要包含前导零的所有数字。

For oct and hex, it's as easy as String.format : 对于oct和hex,它就像String.format一样简单:

assert String.format("%03x", 16) == "010";
assert String.format("%03o", 8) == "010";

使用番石榴你可以写:

String intAsString = Strings.padStart(Integer.toString(12345, 8), 10, '0');

How about this (standard Java): 这个怎么样(标准Java):

private final static String ZEROES = "0000000000";

// ...

String s = Integer.toString(12345, 8);
String intAsString = s.length() <= 10 ? ZEROES.substring(s.length()) + s : s;

Printing out a HEX number, for example, with ZERO padding: 打印出一个十六进制数字,例如,使用ZERO填充:

System.out.println(String.format("%08x", 1234));

Will give the following output, with the padding included: 将提供以下输出,包括填充:

000004d2

Replacing x with OCTAL's associated formatting character will do the same, probably. 用OCTAL的相关格式化字符替换x也可能会这样做。

Here's a more reuseable alternative with help of StringBuilder . StringBuilder帮助下,这是一个更可重用的替代方案。

public static String padZero(int number, int radix, int length) {
    String string = Integer.toString(number, radix);
    StringBuilder builder = new StringBuilder().append(String.format("%0" + length + "d", 0));
    return builder.replace(length - string.length(), length, string).toString();
}

The Guava example as posted by ColinD is by the way pretty slick. 由ColinD发布的Guava示例非常漂亮。

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

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