Example #1
1
  static ByteStream pack(String format, FormatDef[] f, int size, int start, PyObject[] args) {
    ByteStream res = new ByteStream();

    int i = start;
    int len = format.length();
    for (int j = 0; j < len; j++) {
      char c = format.charAt(j);
      if (j == 0 && (c == '@' || c == '<' || c == '>' || c == '=' || c == '!')) continue;
      if (Character.isWhitespace(c)) continue;
      int num = 1;
      if (Character.isDigit(c)) {
        num = Character.digit(c, 10);
        while (++j < len && Character.isDigit((c = format.charAt(j))))
          num = num * 10 + Character.digit(c, 10);
        if (j >= len) break;
      }

      FormatDef e = getentry(c, f);

      // Fill pad bytes with zeros
      int nres = align(res.size(), e) - res.size();
      while (nres-- > 0) res.writeByte(0);
      i += e.doPack(res, num, i, args);
    }

    if (i < args.length) throw StructError("too many arguments for pack format");

    return res;
  }
Example #2
0
  /**
   * Converts a String of hex characters into an array of bytes.
   *
   * @param s A string of hex characters (upper case or lower) of even length.
   * @param out A byte array of length at least s.length()/2 + off
   * @param off The first byte to write of the array
   */
  public static final void hexToBytes(String s, byte[] out, int off)
      throws NumberFormatException, IndexOutOfBoundsException {
    int slen = s.length();
    if ((slen % 2) != 0) {
      s = '0' + s;
    }

    if (out.length < off + slen / 2) {
      throw new IndexOutOfBoundsException(
          "Output buffer too small for input (" //$NON-NLS-1$
              + out.length
              + "<" //$NON-NLS-1$
              + off
              + slen / 2
              + ")"); //$NON-NLS-1$
    }

    // Safe to assume the string is even length

    byte b1, b2;
    for (int i = 0; i < slen; i += 2) {
      b1 = (byte) Character.digit(s.charAt(i), 16);
      b2 = (byte) Character.digit(s.charAt(i + 1), 16);
      if (b1 < 0 || b2 < 0) {
        throw new NumberFormatException();
      }
      out[off + i / 2] = (byte) (b1 << 4 | b2);
    }
  }
Example #3
0
 private void escapeChar() {
   nextChar();
   switch (c) {
     case 34: // '"'
     case 39: // '\''
     case 92: // '\\'
     case 98: // 'b'
     case 102: // 'f'
     case 110: // 'n'
     case 114: // 'r'
     case 116: // 't'
       lastLiteral = c;
       nextChar();
       return;
   }
   int i = Character.digit((char) c, 8);
   if (i >= 0) {
     lastLiteral = 0;
     int j = i >= 4 ? 2 : 3;
     do {
       lastLiteral = (lastLiteral << 3) + i;
       nextChar();
       i = Character.digit((char) c, 8);
     } while (i >= 0 && --j > 0);
     return;
   } else {
     report(new Failure(getPos(), "Syntax error in escape sequence"));
     return;
   }
 }
 /**
  * Parse an integer located between 2 given offsets in a string
  *
  * @param value the string to parse
  * @param beginIndex the start index for the integer in the string
  * @param endIndex the end index for the integer in the string
  * @return the int
  * @throws NumberFormatException if the value is not a number
  */
 private static int parseInt(String value, int beginIndex, int endIndex)
     throws NumberFormatException {
   if (beginIndex < 0 || endIndex > value.length() || beginIndex > endIndex) {
     throw new NumberFormatException(value);
   }
   // use same logic as in Integer.parseInt() but less generic we're not supporting negative values
   int i = beginIndex;
   int result = 0;
   int digit;
   if (i < endIndex) {
     digit = Character.digit(value.charAt(i++), 10);
     if (digit < 0) {
       throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
     }
     result = -digit;
   }
   while (i < endIndex) {
     digit = Character.digit(value.charAt(i++), 10);
     if (digit < 0) {
       throw new NumberFormatException("Invalid number: " + value.substring(beginIndex, endIndex));
     }
     result *= 10;
     result -= digit;
   }
   return -result;
 }
Example #5
0
 /**
  * Read an optional signed integer. If there is no integer in the input stream, return 1. For
  * excessively large exponents, return Integer.MIN_VALUE or Integer.MAX_VALUE.
  */
 public int readOptionalExponent() throws java.io.IOException {
   int sign = read();
   boolean overflow = false;
   int c;
   if (sign == '+' || sign == '-') c = read();
   else {
     c = sign;
     sign = 0;
   }
   int value;
   if (c < 0 || (value = Character.digit((char) c, 10)) < 0) {
     if (sign != 0) error("exponent sign not followed by digit");
     value = 1;
   } else {
     int max = (Integer.MAX_VALUE - 9) / 10;
     for (; ; ) {
       c = read();
       int d = Character.digit((char) c, 10);
       if (d < 0) break;
       if (value > max) overflow = true;
       value = 10 * value + d;
     }
   }
   if (c >= 0) unread(c);
   if (sign == '-') value = -value;
   if (overflow) return sign == '-' ? Integer.MIN_VALUE : Integer.MAX_VALUE;
   return value;
 }
Example #6
0
  public final boolean[] encode(String s) {
    int l = s.length();
    if (l % 2 != 0) {
      throw new IllegalArgumentException("The lenght of the input should be even");
    }
    if (l > 80) {
      throw new IllegalArgumentException(
          (new StringBuilder("Requested contents should be less than 80 digits long, but got "))
              .append(l)
              .toString());
    }
    boolean aflag[] = new boolean[l * 9 + 9];
    int j = appendPattern(aflag, 0, START_PATTERN, true);
    for (int i = 0; i < l; i += 2) {
      int i1 = Character.digit(s.charAt(i), 10);
      int j1 = Character.digit(s.charAt(i + 1), 10);
      int ai[] = new int[18];
      for (int k = 0; k < 5; k++) {
        ai[k << 1] = ITFReader.PATTERNS[i1][k];
        ai[(k << 1) + 1] = ITFReader.PATTERNS[j1][k];
      }

      j += appendPattern(aflag, j, ai, true);
    }

    appendPattern(aflag, j, END_PATTERN, true);
    return aflag;
  }
 /**
  * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped
  * characters are converted back to their original representation.
  *
  * @param bytes array of URL safe characters
  * @return array of original bytes
  * @throws DecoderException Thrown if URL decoding is unsuccessful
  */
 public static final byte[] decodeUrl(byte[] bytes) throws DecoderException {
   if (bytes == null) {
     return null;
   }
   ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   for (int i = 0; i < bytes.length; i++) {
     int b = bytes[i];
     if (b == '+') {
       buffer.write(' ');
     } else if (b == '%') {
       try {
         int u = Character.digit((char) bytes[++i], 16);
         int l = Character.digit((char) bytes[++i], 16);
         if (u == -1 || l == -1) {
           throw new DecoderException("Invalid URL encoding");
         }
         buffer.write((char) ((u << 4) + l));
       } catch (ArrayIndexOutOfBoundsException e) {
         throw new DecoderException("Invalid URL encoding");
       }
     } else {
       buffer.write(b);
     }
   }
   return buffer.toByteArray();
 }
 public static byte[] fromHex(String s) {
   if (s != null) {
     try {
       StringBuilder sb = new StringBuilder(s.length());
       for (int i = 0; i < s.length(); i++) {
         char ch = s.charAt(i);
         if (!Character.isWhitespace(ch)) {
           sb.append(ch);
         }
       }
       s = sb.toString();
       int len = s.length();
       byte[] data = new byte[len / 2];
       for (int i = 0; i < len; i += 2) {
         int hi = (Character.digit(s.charAt(i), 16) << 4);
         int low = Character.digit(s.charAt(i + 1), 16);
         if (hi >= 256 || low < 0 || low >= 16) {
           return null;
         }
         data[i / 2] = (byte) (hi | low);
       }
       return data;
     } catch (Exception ignored) {
     }
   }
   return null;
 }
 public static byte[] decodeQuotedPrintable(final byte[] bytes) {
   if (bytes == null) {
     return null;
   }
   final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   for (int i = 0; i < bytes.length; i++) {
     final int b = bytes[i];
     if (b == '=') {
       try {
         final int u = Character.digit((char) bytes[++i], 16);
         final int l = Character.digit((char) bytes[++i], 16);
         buffer.write((char) ((u << 4) + l));
       } catch (Exception e) {
         FileLog.e("tmessages", e);
         return null;
       }
     } else {
       buffer.write(b);
     }
   }
   byte[] array = buffer.toByteArray();
   try {
     buffer.close();
   } catch (Exception e) {
     FileLog.e("tmessages", e);
   }
   return array;
 }
Example #10
0
  static int calcsize(String format, FormatDef[] f) {
    int size = 0;

    int len = format.length();
    for (int j = 0; j < len; j++) {
      char c = format.charAt(j);
      if (j == 0 && (c == '@' || c == '<' || c == '>' || c == '=' || c == '!')) continue;
      if (Character.isWhitespace(c)) continue;
      int num = 1;
      if (Character.isDigit(c)) {
        num = Character.digit(c, 10);
        while (++j < len && Character.isDigit((c = format.charAt(j)))) {
          int x = num * 10 + Character.digit(c, 10);
          if (x / 10 != num) throw StructError("overflow in item count");
          num = x;
        }
        if (j >= len) break;
      }

      FormatDef e = getentry(c, f);

      int itemsize = e.size;
      size = align(size, e);
      int x = num * itemsize;
      size += x;
      if (x / itemsize != num || size < 0) throw StructError("total struct size too long");
    }
    return size;
  }
Example #11
0
  public static void checkCardId(String arg0, String errorMsg) throws Exception {
    if (arg0 == null) throw new Exception(errorMsg);

    String personId = ((String) arg0).toUpperCase();

    Pattern pattern = Pattern.compile("^\\p{Upper}{1}\\d{9}", Pattern.CASE_INSENSITIVE);
    final char[] FIRSTWORD = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
      'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };
    final int[] FIRSTWORDNUMBER = {
      1, 10, 19, 28, 37, 46, 55, 64, 39, 73, 82, 2, 11, 20, 48, 29, 38, 47, 56, 65, 74, 83, 21, 3,
      12, 30
    };

    Matcher matcher = pattern.matcher(personId);
    if (matcher.matches()) {
      int verifyNumber = 0;
      // 英文字母的轉碼數字
      verifyNumber = FIRSTWORDNUMBER[Arrays.binarySearch(FIRSTWORD, personId.charAt(0))];
      // 身份證字號第1~8個數字依次取出乘以8~1
      for (int i = 0; i < 8; i++) {
        verifyNumber += Character.digit(personId.charAt(i + 1), 10) * (8 - i);
      }
      // 10 - 上述總和除10之餘數
      verifyNumber = 10 - (verifyNumber % 10);
      if (verifyNumber == Character.digit(personId.charAt(9), 10) || verifyNumber == 10) {
        return;
      }
    }
    throw new Exception(errorMsg);
  }
Example #12
0
  /**
   * Parse a mac adress from the canonical string representation as 6 hex bytes separated by colons
   * (01:02:03:04:05:06).
   *
   * @param macString - a mac address in canonical string representation
   * @return the parsed MacAddress
   * @throws IllegalArgumentException if macString is not a valid mac adddress
   */
  @Nonnull
  public static MacAddress of(@Nonnull final String macString) throws IllegalArgumentException {
    if (macString == null) {
      throw new NullPointerException("macString must not be null");
    }

    int index = 0;
    int shift = 40;
    long raw = 0;

    if (macString.length() != MAC_STRING_LENGTH) {
      throw new IllegalArgumentException(FORMAT_ERROR + macString);
    }

    while (shift >= 0) {
      int digit1 = Character.digit(macString.charAt(index++), 16);
      int digit2 = Character.digit(macString.charAt(index++), 16);
      if ((digit1 < 0) || (digit2 < 0))
        throw new IllegalArgumentException(FORMAT_ERROR + macString);
      raw |= ((long) (digit1 << 4 | digit2)) << shift;

      if (shift == 0) break;
      if (macString.charAt(index++) != ':')
        throw new IllegalArgumentException(FORMAT_ERROR + macString);
      shift -= 8;
    }
    return MacAddress.of(raw);
  }
Example #13
0
  private static byte[] a(String s) {
    boolean flag1 = true;
    byte abyte0[];
    int j;
    boolean flag;
    if (s.length() % 2 == 0) {
      flag = true;
    } else {
      flag = false;
    }
    b.b(flag);
    j = s.length();
    abyte0 = new byte[j << 1];
    for (int i = 0; i < j; i += 2) {
      abyte0[i / 2] =
          (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }

    if (abyte0.length <= 188) {
      flag = flag1;
    } else {
      flag = false;
    }
    b.b(flag);
    return a.a(abyte0, 188, (byte) -1);
  }
 /**
  * Inverse function of {@link Util#rawEncode(String)}
  *
  * @param s the encoded string.
  * @return the decoded string.
  */
 @NonNull
 public static String rawDecode(@NonNull String s) {
   final byte[] bytes; // should be US-ASCII but we can be tolerant
   try {
     bytes = s.getBytes("UTF-8");
   } catch (UnsupportedEncodingException e) {
     throw new IllegalStateException(
         "JLS specification mandates UTF-8 as a supported encoding", e);
   }
   final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   for (int i = 0; i < bytes.length; i++) {
     final int b = bytes[i];
     if (b == '%' && i + 2 < bytes.length) {
       final int u = Character.digit((char) bytes[++i], 16);
       final int l = Character.digit((char) bytes[++i], 16);
       if (u != -1 && l != -1) {
         buffer.write((char) ((u << 4) + l));
         continue;
       }
       // should be a valid encoding but we can be tolerant
       i -= 2;
     }
     buffer.write(b);
   }
   try {
     return new String(buffer.toByteArray(), "UTF-8");
   } catch (UnsupportedEncodingException e) {
     throw new IllegalStateException(
         "JLS specification mandates UTF-8 as a supported encoding", e);
   }
 }
Example #15
0
 private static int parseInt(String paramString, int paramInt1, int paramInt2)
   throws NumberFormatException
 {
   if ((paramInt1 < 0) || (paramInt2 > paramString.length()) || (paramInt1 > paramInt2))
     throw new NumberFormatException(paramString);
   int i;
   int j;
   if (paramInt1 < paramInt2)
   {
     i = paramInt1 + 1;
     int n = Character.digit(paramString.charAt(paramInt1), 10);
     if (n < 0)
       throw new NumberFormatException("Invalid number: " + paramString);
     j = -n;
   }
   while (true)
     if (i < paramInt2)
     {
       int k = i + 1;
       int m = Character.digit(paramString.charAt(i), 10);
       if (m < 0)
         throw new NumberFormatException("Invalid number: " + paramString);
       j = j * 10 - m;
       i = k;
     }
     else
     {
       return -j;
       i = paramInt1;
       j = 0;
     }
 }
Example #16
0
  /*
  http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
   */
  public static byte[] hexStringToByteArray(String s) {
    int len = s.length();

    if (len % 2 == 1) {
      s = "0" + s;
      len++;
    }

    final byte[] data = new byte[len / 2];

    for (int i = 0; i < len; i += 2) {
      final char c1 = s.charAt(i);

      final char c2 = s.charAt(i + 1);

      final int d1 = Character.digit(c1, 16) << 4;

      final int d2 = Character.digit(c2, 16) & 0x0f;

      final byte b = (byte) (d1 | d2);

      /*
      System.err.println("hex->byte: "+c1+" "+c2+" "+d1+" "+d2+" "+b);
      System.err.flush();
      */

      data[i / 2] = b;
    }

    return data;
  }
Example #17
0
 /** {@inheritDoc} */
 @Override
 public String decode(String encodedText) {
   if (encodedText == null) return null;
   if (encodedText.length() == 0) return encodedText;
   final StringBuilder result = new StringBuilder();
   final CharacterIterator iter = new StringCharacterIterator(encodedText);
   for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
     if (c == ESCAPE_CHARACTER) {
       boolean foundEscapedCharacter = false;
       // Found the first character in a potential escape sequence, so grab the next two characters
       // ...
       char hexChar1 = iter.next();
       char hexChar2 = hexChar1 != CharacterIterator.DONE ? iter.next() : CharacterIterator.DONE;
       if (hexChar2 != CharacterIterator.DONE) {
         // We found two more characters, but ensure they form a valid hexadecimal number ...
         int hexNum1 = Character.digit(hexChar1, 16);
         int hexNum2 = Character.digit(hexChar2, 16);
         if (hexNum1 > -1 && hexNum2 > -1) {
           foundEscapedCharacter = true;
           result.append((char) (hexNum1 * 16 + hexNum2));
         }
       }
       if (!foundEscapedCharacter) {
         result.append(c);
         if (hexChar1 != CharacterIterator.DONE) result.append(hexChar1);
         if (hexChar2 != CharacterIterator.DONE) result.append(hexChar2);
       }
     } else {
       result.append(c);
     }
   }
   return result.toString();
 }
	public static byte[] hexStringToByteArray(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
		}
		return data;
	}
Example #19
0
  public int readByte() throws FatekIOException {

    char[] buf = new char[2];
    if (read(buf) != 2) {
      throw new FatekUnexpectedEOSException();
    }

    return (Character.digit(buf[0], 16) << 4 | Character.digit(buf[1], 16)) & 0xff;
  }
Example #20
0
  // http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
  public static byte[] StringToBytes(String s) {
    byte[] data = new byte[s.length() / 2];

    for (int i = 0; i < s.length(); i += 2)
      data[i / 2] =
          (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));

    return data;
  }
  public long element() {

    long result = 0;
    boolean negative = false;
    int i = 0, max = tokenNumBytes;
    long limit;
    long multmin;
    int digit;

    if (max > 0) {
      if (tokenCharAt(0) == '-') {
        negative = true;
        limit = Long.MIN_VALUE;
        i++;
      } else {
        limit = -Long.MAX_VALUE;
      }

      multmin = negative ? MULTMIN_RADIX_TEN : N_MULTMAX_RADIX_TEN;

      if (i < max) {
        digit = Character.digit(tokenCharAt(i++), RADIX_TEN);
        if (digit < 0) {
          throw new NumberFormatException(toString());
        } else {
          result = -digit;
        }
      }
      while (i < max) {
        // Accumulating negatively avoids surprises near MAX_VALUE
        digit = Character.digit(tokenCharAt(i++), RADIX_TEN);
        if (digit < 0) {
          throw new NumberFormatException(toString());
        }
        if (result < multmin) {
          throw new NumberFormatException(toString());
        }
        result *= RADIX_TEN;
        if (result < limit + digit) {
          throw new NumberFormatException(toString());
        }
        result -= digit;
      }
    } else {
      throw new NumberFormatException(toString());
    }
    if (negative) {
      if (i > 1) {
        return result;
      } else {
          /* Only got "-" */
        throw new NumberFormatException(toString());
      }
    } else {
      return -result;
    }
  }
Example #22
0
  /**
   * Convert the bytes within the specified range of the given byte array into a signed integer in
   * the given radix . The range extends from <code>start</code> till, but not including <code>end
   * </code>.
   *
   * <p>Based on java.lang.Integer.parseInt()
   */
  public static int parseInt(byte[] b, int start, int end, int radix) throws NumberFormatException {
    if (b == null) throw new NumberFormatException("null");

    int result = 0;
    boolean negative = false;
    int i = start;
    int limit;
    int multmin;
    int digit;

    if (end > start) {
      if (b[i] == '-') {
        negative = true;
        limit = Integer.MIN_VALUE;
        i++;
      } else {
        limit = -Integer.MAX_VALUE;
      }
      multmin = limit / radix;
      if (i < end) {
        digit = Character.digit((char) b[i++], radix);
        if (digit < 0) {
          throw new NumberFormatException("illegal number: " + toString(b, start, end));
        } else {
          result = -digit;
        }
      }
      while (i < end) {
        // Accumulating negatively avoids surprises near MAX_VALUE
        digit = Character.digit((char) b[i++], radix);
        if (digit < 0) {
          throw new NumberFormatException("illegal number");
        }
        if (result < multmin) {
          throw new NumberFormatException("illegal number");
        }
        result *= radix;
        if (result < limit + digit) {
          throw new NumberFormatException("illegal number");
        }
        result -= digit;
      }
    } else {
      throw new NumberFormatException("illegal number");
    }
    if (negative) {
      if (i > start + 1) {
        return result;
      } else {
          /* Only got "-" */
        throw new NumberFormatException("illegal number");
      }
    } else {
      return -result;
    }
  }
Example #23
0
 protected byte[] hexStringToByteArray(String paramString) {
   int i = paramString.length();
   byte[] arrayOfByte = new byte[i / 2];
   for (int j = 0; j < i; j += 2)
     arrayOfByte[(j / 2)] =
         (byte)
             ((Character.digit(paramString.charAt(j), 16) << 4)
                 + Character.digit(paramString.charAt(j + 1), 16));
   return arrayOfByte;
 }
Example #24
0
 /**
  * 16进制表示的字符串转换为字节数组。
  *
  * @param s 16进制表示的字符串
  * @return byte[] 字节数组
  */
 public static byte[] hexStringToByteArray(String s) {
   int len = s.length();
   byte[] d = new byte[len / 2];
   for (int i = 0; i < len; i += 2) {
     // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
     d[i / 2] =
         (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
   }
   return d;
 }
Example #25
0
 private static byte[] hex2bytes(String hex) {
   // Convert hex string to byte array
   int len = hex.length();
   byte[] result = new byte[len / 2];
   for (int i = 0; i < len; i += 2)
     result[i / 2] =
         (byte)
             ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
   return result;
 }
Example #26
0
 // Converts a string to bytes
 // From http://stackoverflow.com/a/140861
 private static byte[] hexStringToByteArray(String s) {
   System.out.println("Sending code: " + s);
   int len = s.length();
   byte[] data = new byte[len / 2];
   for (int i = 0; i < len; i += 2) {
     data[i / 2] =
         (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
   }
   return data;
 }
Example #27
0
 protected byte[] hexStringToByteArray(String s) {
   // From
   // http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
   int len = s.length();
   byte[] data = new byte[len / 2];
   for (int i = 0; i < len; i += 2) {
     data[i / 2] =
         (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
   }
   return data;
 }
 /**
  * Converts hex values from strings to byte arra
  *
  * @param hexString string of hex-encoded values
  * @return decoded byte array
  */
 protected byte[] hexStringToByteArray(String hexString) {
   int len = hexString.length();
   byte[] data = new byte[len / 2];
   for (int i = 0; i < len; i += 2) {
     data[i / 2] =
         (byte)
             ((Character.digit(hexString.charAt(i), 16) << 4)
                 + Character.digit(hexString.charAt(i + 1), 16));
   }
   return data;
 }
Example #29
0
 private static byte[] hexStringDigestToByteArray(String hexDigest) {
   int len = hexDigest.length();
   byte[] digest = new byte[len / 2];
   for (int i = 0; i < len; i += 2) {
     digest[i / 2] =
         (byte)
             ((Character.digit(hexDigest.charAt(i), 16) << 4)
                 + Character.digit(hexDigest.charAt(i + 1), 16));
   }
   return digest;
 }
Example #30
0
  /**
   * Converts the given {@code string} into an UUID.
   *
   * @param string Unlike {@link UUID#fromString}, dashes may be omitted.
   * @throws UuidFormatException If the given string is {@code null} or isn't a valid UUID.
   */
  public static UUID fromString(String string) {
    if (string == null) {
      throw new UuidFormatException("Can't convert a null into an UUID!");
    }

    PARSE:
    {
      int length = string.length();

      if (length == 32 || length == 36) {
        char[] letters = string.toCharArray();
        int letterIndex = 0;
        char letter;
        int letterDigit;

        long msb = 0;
        long lsb = 0;

        for (int i = 0; letterIndex < length && i < 16; ++letterIndex) {
          letter = letters[letterIndex];

          if (letter != '-') {
            letterDigit = Character.digit(letter, 16);

            if (letterDigit < 0) {
              break PARSE;
            }

            msb = (msb << 4) | letterDigit;
            ++i;
          }
        }

        for (int i = 0; letterIndex < length && i < 16; ++letterIndex) {
          letter = letters[letterIndex];

          if (letter != '-') {
            letterDigit = Character.digit(letter, 16);

            if (letterDigit < 0) {
              break PARSE;
            }

            lsb = (lsb << 4) | letterDigit;
            ++i;
          }
        }

        return new UUID(msb, lsb);
      }
    }

    throw new UuidFormatException("[" + string + "] isn't a valid UUID!");
  }