Android Hex String to Byte Array Convert hexStringToBytes(String s)

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

Description

Converts a hex String to a byte array.

License

Apache License

Parameter

Parameter Description
s A string of hexadecimal characters, must be an even number of chars long

Exception

Parameter Description
RuntimeException on invalid format

Return

byte array representation

Declaration

public static byte[] hexStringToBytes(String s) 

Method Source Code

//package com.java2s;
/*/*  w  w  w  . ja v a  2  s. c o m*/
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed 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 {
    /**
     * Converts a hex String to a byte array.
     *
     * @param s A string of hexadecimal characters, must be an even number of
     *          chars long
     *
     * @return byte array representation
     *
     * @throws RuntimeException on invalid format
     */
    public static byte[] hexStringToBytes(String s) {
        byte[] ret;

        if (s == null)
            return null;

        int sz = s.length();

        ret = new byte[sz / 2];

        for (int i = 0; i < sz; i += 2) {
            ret[i / 2] = (byte) ((hexCharToInt(s.charAt(i)) << 4) | hexCharToInt(s
                    .charAt(i + 1)));
        }

        return ret;
    }

    static int hexCharToInt(char c) {
        if (c >= '0' && c <= '9')
            return (c - '0');
        if (c >= 'A' && c <= 'F')
            return (c - 'A' + 10);
        if (c >= 'a' && c <= 'f')
            return (c - 'a' + 10);

        throw new RuntimeException("invalid hex char '" + c + "'");
    }
}

Related

  1. hexStr2Bytes(String src)
  2. hexStr2Str(String hexStr)
  3. toByte(String hexString)
  4. toBytesFromHexString(String digits)
  5. hexStringToBytes(String s)
  6. decodeHex(String str)
  7. fromHex(String hex)
  8. hexStringToByteArray(String s)