Java中带有零的左填充整数(非十进制格式)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3149692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Left padding integers (non-decimal format) with zeros in Java
提问by Andreas Dolk
The question has been answered for integers printed in decimal format, but I'm looking for an elegantway to do the same with integers in non-decimalformat (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 等)的二进制数,其中想要包含前导零的所有数字。
采纳答案by Jesper
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;
回答by ColinD
回答by gustafc
For oct and hex, it's as easy as String.format
:
对于八进制和十六进制,它很简单String.format
:
assert String.format("%03x", 16) == "010";
assert String.format("%03o", 8) == "010";
回答by BalusC
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 示例非常漂亮。
回答by Armandt
Printing out a HEX number, for example, with ZERO padding:
打印出一个十六进制数,例如,用零填充:
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.
用八进制的关联格式化字符替换 x 可能会做同样的事情。