format UUID - Java java.util

Java examples for java.util:UUID

Description

format UUID

Demo Code


//package com.java2s;

public class Main {
    private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public static String formatUUID(byte[] data) throws Exception {
        if (data.length != 16) {
            throw new Exception("invalid UUID length");
        }//w w w  .  j  ava2s  . c  om
        StringBuffer sb = new StringBuffer(2 * 16 + 4);

        sb.append(dumpHex(data, 0, 4));
        sb.append('-');

        sb.append(dumpHex(data, 4, 2));
        sb.append('-');

        sb.append(dumpHex(data, 6, 2));
        sb.append('-');

        sb.append(dumpHex(data, 8, 2));
        sb.append('-');

        sb.append(dumpHex(data, 10, 6));
        return sb.toString().toLowerCase();
    }

    /**
     * Returns the RAW bytes as hexadecimal string.
     * This method is used for debugging.
     *
     * @param data The RAW bytes.
     * @return The hexadecimal string.
     */
    public static String dumpHex(byte[] data, int offset, int length) {
        char[] hex = new char[2 * length];
        for (int i = 0; i < length; ++i) {
            final int b = data[offset + i] & 0xFF;
            hex[2 * i + 0] = HEX[b >>> 4];
            hex[2 * i + 1] = HEX[b & 0x0F];
        }

        return new String(hex);
    }

    public static String dumpHex(byte[] data) {
        return data != null ? dumpHex(data, 0, data.length) : "null";
    }

    /**
     * Returns the integer as hexadecimal string.
     *
     * @param val The integer value.
     * @param width The number of characters to dump.
     * @return The hexadecimal string.
     */
    public static String dumpHex(long val, int width) {
        char[] hex = new char[width];
        for (int i = 0; i < width; ++i) {
            final long b = (val >>> ((width - 1 - i) * 4));
            hex[i] = HEX[(int) b & 0x0F];
        }

        return new String(hex);
    }
}

Related Tutorials