SVD
SVD

Reputation: 4753

Arbitrary radix padded format

I wonder if there's a standard way in Java to format an integer number into an arbitrary radix with left-padded zeroes. E.g. for radix-32, padded to 4 characters length, if I have a number 30, I'd like to get a string like "000t" or if I have 300 I should get "008z" (t and 8z not necessarily correspond to base-32 notation of 30 and 300, it's just an example).

Upvotes: 1

Views: 1752

Answers (1)

Andrew
Andrew

Reputation: 7516

Convert the integer to a string in the radix that you need, then use the string formatter to pad the output string. The string formatter will pad with spaces, which you then need to convert to zeros.

Here's an example:

int num = 300;
String numString = Integer.toString(num, 30);

String padded = String.format("%1$#4s", numString).replace(' ', '0'); // "00ao"

The second argument to toString is the radix: 30 in this case.

The first argument to String.format is the format string, which I took from here. The value you care most about is the 4 in the middle of string: that's the total number of characters that you want in the string.

Upvotes: 2

Related Questions