Java Byte Array Create toByteArray(String uid)

Here you can find the source of toByteArray(String uid)

Description

Converts a UID formatted String to a byte[].

License

Open Source License

Parameter

Parameter Description
uid String representing a 128-bit UID.

Return

byte[] 16 bytes in length representing the 128-bits of the UID or null if the uid could not be converted.

Declaration

public static byte[] toByteArray(String uid) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from  w w  w  .  j  a  v  a 2s  .co m*/
     * Converts a UID formatted String to a byte[]. The UID must be in the
     * format generated by createUID, otherwise null is returned.
     *
     * @param uid String representing a 128-bit UID.
     *
     * @return byte[] 16 bytes in length representing the 128-bits of the
     * UID or null if the uid could not be converted.
     */
    public static byte[] toByteArray(String uid) {
        if (isUID(uid)) {
            byte[] result = new byte[16];
            char[] chars = uid.toCharArray();
            int r = 0;

            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == '-')
                    continue;
                int h1 = Character.digit(chars[i], 16);
                i++;
                int h2 = Character.digit(chars[i], 16);
                result[r++] = (byte) (((h1 << 4) | h2) & 0xFF);
            }
            return result;
        }

        return null;
    }

    /**
     * A utility method to check whether a String value represents a
     * correctly formatted UID value. UID values are expected to be
     * in the format generated by createUID(), implying that only
     * capitalized A-F characters in addition to 0-9 digits are
     * supported.
     *
     * @param uid The value to test whether it is formatted as a UID.
     *
     * @return Returns true if the value is formatted as a UID.
     */
    public static boolean isUID(String uid) {
        if (uid != null && uid.length() == 36) {
            char[] chars = uid.toCharArray();
            for (int i = 0; i < 36; i++) {
                char c = chars[i];

                // Check for correctly placed hyphens
                if (i == 8 || i == 13 || i == 18 || i == 23) {
                    if (c != '-') {
                        return false;
                    }
                }
                // We allow capital alpha-numeric hex digits only
                else if (c < 48 || c > 70 || (c > 57 && c < 65)) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }
}

Related

  1. toByteArray(String str)
  2. toByteArray(String str, String separator)
  3. toByteArray(String string)
  4. toByteArray(String string)
  5. toByteArray(String strTransInfo)
  6. toByteArray(String value)
  7. toByteArray(String[] anArray)
  8. toByteArray1D(int[][] d)
  9. toByteArrayBE(byte b)