Creating a UUID from a string with no dashes

前端 未结 10 2259
臣服心动
臣服心动 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条回答
  •  醉话见心
    2020-11-29 01:32

    Regexp solution is probably faster, but you can also look at that :)

    String withoutDashes = "44e128a5-ac7a-4c9a-be4c-224b6bf81b20".replaceAll("-", "");      
    BigInteger bi1 = new BigInteger(withoutDashes.substring(0, 16), 16);                
    BigInteger bi2 = new BigInteger(withoutDashes.substring(16, 32), 16);
    UUID uuid = new UUID(bi1.longValue(), bi2.longValue());
    String withDashes = uuid.toString();
    

    By the way, conversion from 16 binary bytes to uuid

      InputStream is = ..binarty input..;
      byte[] bytes = IOUtils.toByteArray(is);
      ByteBuffer bb = ByteBuffer.wrap(bytes);
      UUID uuidWithDashesObj = new UUID(bb.getLong(), bb.getLong());
      String uuidWithDashes = uuidWithDashesObj.toString();
    

提交回复
热议问题