Left integer (without decimal format) with zeros in Java

The answer to the question answered integers printed in decimal format , but I'm looking for an elegant way to do the same with non-decimal integers (like binary, octal, hexadecimal).

Creating lines like this is easy:

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

will create a String with the octal representation of the integer value 12345. But how to format it so that the string has 10 digits, in addition to calculating the number of zeros and assembling a new line "manually".

A typical use case would be to create binary numbers with a fixed number of bits (for example, 16, 32, ...), in which we would like to have all the digits, including leading zeros.

+12
java
Jun 30 '10 at 13:30
source share
5 answers

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; 
+5
Jun 30 '10 at 15:29
source share

For octa and hexadecimal, this is just like String.format :

 assert String.format("%03x", 16) == "010"; assert String.format("%03o", 8) == "010"; 
+19
Jun 30 2018-10-30
source share

With Guava, you can simply write:

 String intAsString = Strings.padStart(Integer.toString(12345, 8), 10, '0'); 
+13
Jun 30 '10 at 13:33
source share

Printout of the HEX number, for example, with the filling in ZERO:

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

Will produce the following result, including the addition:

 000004d2 

Replacing x with the format character associated with OCTAL will do the same, perhaps.

+3
Jul 02 '14 at 7:48
source share

Here's a more StringBuilder alternative with 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 published by ColinD, by the way, is pretty good.

+2
Jun 30 '10 at 15:51
source share



All Articles