Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'.

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.

like image 976
Andreas Dolk Avatar asked Jun 30 '10 13:06

Andreas Dolk


People also ask

How do you add zeros to a String in Java?

The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.

What is a zero padded number?

Zero padding is a technique typically employed to make the size of the input sequence equal to a power of two. In zero padding, you add zeros to the end of the input sequence so that the total number of samples is equal to the next higher power of two.

How do you keep leading zeros in Java?

To display numbers with leading zeros in Java, useDecimalFormat("000000000000").


1 Answers

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

assert String.format("%03x", 16) == "010";
assert String.format("%03o", 8) == "010";
like image 196
gustafc Avatar answered Oct 06 '22 02:10

gustafc