Java Base16 Encode base16toByte(String str)

Here you can find the source of base16toByte(String str)

Description

baseto Byte

License

Apache License

Declaration

public static final byte[] base16toByte(String str) 

Method Source Code

//package com.java2s;
/**//from www  .  ja va 2  s  .  c  o m
 * Base16Util.java
 *
 * Copyright 2011 Niolex, Inc.
 *
 * Niolex licenses this file to you under the Apache License, version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License.  You may obtain a copy of the License at:
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

public class Main {
    private static final byte[] CHAR_TO_DIGIT = new byte[256];

    public static final byte[] base16toByte(String str) {
        if (str == null)
            throw new IllegalArgumentException("The parameter should not be null!");
        final char[] hex = str.toLowerCase().toCharArray();
        final int hexLen = str.length();
        if (hexLen % 2 != 0)
            throw new IllegalArgumentException("The parameter length should be even!");
        byte[] bytes = new byte[hexLen / 2];
        for (int i = 0, j = 0; i < hexLen; i += 2, ++j) {
            if (hex[i] > 255 || hex[i + 1] > 255) {
                throw new IllegalArgumentException("The parameter contains invalid charater!");
            }
            bytes[j] = (byte) (CHAR_TO_DIGIT[hex[i]] << 4 | CHAR_TO_DIGIT[hex[i + 1]]);
        }
        return bytes;
    }
}

Related

  1. base16Encode(byte[] data)
  2. base16ToInt(char c)