Java Hex to Byte Array convertHexToBytes(String s)

Here you can find the source of convertHexToBytes(String s)

Description

Convert a hex encoded string to a byte array.

License

Apache License

Parameter

Parameter Description
s the hex encoded string

Return

the byte array

Declaration

public static byte[] convertHexToBytes(String s) 

Method Source Code

//package com.java2s;
/*/*from   w  ww  .j a  v  a2 s.  c  om*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF 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 {
    /**
     * Convert a hex encoded string to a byte array.
     *
     * @param s the hex encoded string
     * @return the byte array
     */
    public static byte[] convertHexToBytes(String s) {
        int len = s.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException(s);
        }
        len /= 2;
        byte[] buff = new byte[len];
        for (int i = 0; i < len; i++) {
            buff[i] = (byte) ((getHexDigit(s, i + i) << 4) | getHexDigit(s, i + i + 1));
        }
        return buff;
    }

    /**
     * Convert the digit at the given position to a hex number.
     *
     * @param s the hex encoded string
     * @param i the index
     * @return the number
     */
    private static int getHexDigit(String s, int i) {
        char c = s.charAt(i);
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'a' && c <= 'f') {
            return c - 'a' + 0xa;
        } else if (c >= 'A' && c <= 'F') {
            return c - 'A' + 0xa;
        } else {
            throw new IllegalArgumentException(s);
        }
    }
}

Related

  1. convertHexStringToByteNoSpace(String s)
  2. convertHexStringToBytes(String hex)
  3. convertHexStringToBytes(String hex)
  4. convertHexToByteArray(String hexString)
  5. convertHexToBytes(String s)