Monday, October 12, 2009

Quick way to create an uppercase letter-only string from a long value.

Today I had to find a quick way to convert the current time in milliseconds into an uppercase letter-only ([A-Z]+) string with possibly minimal length. java.util.UUID did not seem to fit well to the purpose as it produces [0..9A..F]+ that requires extra conversion so I come up with the following:

    public static String makeUppercaseLetterOnlyStringFromCurrentTime() {
        final long ts = System.currentTimeMillis();
        // convert the value to range of 0..9a...z characters
        final String chars = Long.toString(ts, 26);
        final StringBuilder sb = new StringBuilder();
        for (byte b : chars.getBytes()) {
            final int ch = (intb;
            // for a digit subtract '0' and add to 'A', 

            // for a letter - subtract 'a' and and add to 'A'
            final int x = b + ((Character.isDigit(b)) 0x11 : -0x20);
            sb.append((charx);
        }
        return sb.toString();
    }

This for sure is not the fastest nor the most efficient approach yet quite straight-forward one. :-)

No comments:

Post a Comment