Creating a UUID from a string with no dashes

前端 未结 10 2238
臣服心动
臣服心动 2020-11-29 01:15

How would I create a java.util.UUID from a string with no dashes?

\"5231b533ba17478798a3f2df37de2aD7\" => #uuid \"5231b533-ba17-4787-98a3-f2df37de2aD7\"
<         


        
10条回答
  •  -上瘾入骨i
    2020-11-29 01:38

    Here is an example that is faster because it doesn't use regexp.

    public class Example1 {
        /**
         * Get a UUID with hyphens from 32 char hexadecimal.
         * 
         * @param string a hexadecimal string
         * @return a UUID string
         */
        public static String toUuidString(String string) {
    
            if (string == null || string.length() != 32) {
                throw new IllegalArgumentException("invalid input string!");
            }
    
            char[] input = string.toCharArray();
            char[] output = new char[36];
    
            System.arraycopy(input, 0, output, 0, 8);
            System.arraycopy(input, 8, output, 9, 4);
            System.arraycopy(input, 12, output, 14, 4);
            System.arraycopy(input, 16, output, 19, 4);
            System.arraycopy(input, 20, output, 24, 12);
    
            output[8] = '-';
            output[13] = '-';
            output[18] = '-';
            output[23] = '-';
    
            return new String(output);
        }
    
        public static void main(String[] args) {
            String example = "daa70a7ffa904841bf9a81a67bdfdb45";
            String canonical = toUuidString(example);
            UUID uuid = UUID.fromString(canonical);
        }
    }
    

提交回复
热议问题