开发者

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

开发者 https://www.devze.com 2023-01-05 10:12 出处:网络
The question has been answered for i开发者_JAVA百科ntegers 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).

The question has been answered for i开发者_JAVA百科ntegers 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'.

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.


For oct and hex, it's as easy as String.format:

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


With Guava you could just write:

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


How about this (standard 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:

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.


Here's a more reuseable alternative with help of 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号