Java Convert via ByteBuffer toGuidString(UUID uuid)

Here you can find the source of toGuidString(UUID uuid)

Description

to Guid String

License

Open Source License

Declaration

public static String toGuidString(UUID uuid) 

Method Source Code

//package com.java2s;
//  License: https://servicestack.net/bsd-license.txt

import java.nio.ByteBuffer;

import java.util.UUID;

public class Main {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String toGuidString(UUID uuid) {
        byte[] guidBytes = toGuidBytes(uuid);
        String to = toHex(guidBytes);
        return to;
    }//from  www.j  a v  a2s.c o  m

    public static byte[] toGuidBytes(UUID theUuid) {
        ByteBuffer first8 = ByteBuffer.allocate(8);
        first8.putLong(theUuid.getMostSignificantBits());
        first8.rewind();

        byte[] first4 = new byte[4];
        first8.get(first4);
        reverse(first4);

        byte[] second2 = new byte[2];
        first8.get(second2);
        reverse(second2);

        byte[] third2 = new byte[2];
        first8.get(third2);
        reverse(third2);

        ByteBuffer converted16 = ByteBuffer.allocate(16).put(first4).put(second2).put(third2);

        ByteBuffer last8 = ByteBuffer.allocate(8);
        last8.putLong(theUuid.getLeastSignificantBits());
        last8.rewind();

        converted16.put(last8);

        return converted16.array();
    }

    public static String toHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static void reverse(byte[] bytes) {
        if (bytes == null)
            return;

        int i = 0;
        int j = bytes.length - 1;
        byte hold;
        while (j > i) {
            hold = bytes[j];
            bytes[j] = bytes[i];
            bytes[i] = hold;
            j--;
            i++;
        }
    }
}

Related

  1. toFloat(byte[] bytes)
  2. toFloat(final byte[] b)
  3. toFloatArray(int[] intArray)
  4. toFloatBytes(List datas)
  5. toGuidBytes(UUID theUuid)
  6. toHex(byte[] bytes)
  7. toHexBytes(byte[] bytes)
  8. toHexString(Number n)
  9. toInt(byte[] bytes)