Zero padding and left padding integers in Java (non decimal format)
•
Java
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 (such as binary, octal, hexadecimal)
Creating such a string is easy:
String intAsString = Integer.toString(12345,8);
A string with an octal representation of the integer value 12345 is created But how to format it so that the string has 10 digits, in addition to calculating the required zeros and manually assembling a new string
A typical use case would be to create binary numbers with fixed digits (e.g. 16,32,...), where one wants to have all numbers including leading zeros
Solution
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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码