I have the following Java code that increases the value of a hex value and returns a string using the following format (where x
is an increasing hex value and 7
is a literal):
xxxx-7xxx-xxxx
The value is increasing from left to right like so and consists of 12 characters:
0000-7000-0001
0000-7000-0002
...
0000-7fff-ffff
0001-7000-0000
The code:
public class GeneratorTemplate {
private static final AtomicLong COUNTER = new AtomicLong(0);
public static String generateTemplate() {
// incrementing the counter
long currentValue = COUNTER.getAndIncrement();
// get 11 character (not 12 because 7 is a literal and appended) hex value represented as string
String rawResult = String.format("%011X", currentValue & 0xFFFFFFFFFFFL);
// append and format values
return (rawResult.substring(0, 4) +
"-7" +
rawResult.substring(4, 7) +
"-" +
rawResult.substring(7)).toLowerCase();
}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(generateTemplate());
}
}
}
It works but I'm sure that this is not efficient.
The performance issue revolves around the fact that I do appending of 7
, hyphens and lowercase manually. I think that if I do this in the format()
method, I'll have gains in performance. In addition, that code would be clearer
I tried to accomplish this in one line but to no avail. This code is obviously incorrect and I wonder how to use the format()
method correctly, so that I won't have to append anything manually:
return String.format("%04X-7%03X-%04X", currentValue & 0xFFFFL, currentValue & 0xFFFL, currentValue & 0xFFFFL);
Could anyone clarify of whether this is possible to do using the format()
method and what the number of F
represents in the parameter (I obviously understand that this is hex but how many F's
should be there)?
Thanks
public static String generateTemplate() {long currentValue = COUNTER.getAndIncrement();StringBuilder sb = new StringBuilder(String.format("%012x", currentValue & 0xFFFFFFFFFFFL));sb.setCharAt(4, '7');sb.insert(4, '-');sb.insert(9, '-');return sb.toString();}