Java Byte Array Create toBytes(String hexString)

Here you can find the source of toBytes(String hexString)

Description

Get the byte representation of an ASCII-HEX string.

License

Apache License

Parameter

Parameter Description
hexString The string to convert to bytes

Return

The byte representation of the ASCII-HEX string.

Declaration

public static byte[] toBytes(String hexString) 

Method Source Code

//package com.java2s;
/**//  w w w .j  a  v a  2  s.c o m
 * Copyright 2011 bccapi.com
 *
 * 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 {
    /**
     * Get the byte representation of an ASCII-HEX string.
     * 
     * @param hexString
     *           The string to convert to bytes
     * @return The byte representation of the ASCII-HEX string.
     */
    public static byte[] toBytes(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0) {
            throw new RuntimeException("Input string must contain an even number of characters");
        }
        char[] hex = hexString.toCharArray();
        int length = hex.length / 2;
        byte[] raw = new byte[length];
        for (int i = 0; i < length; i++) {
            int high = Character.digit(hex[i * 2], 16);
            int low = Character.digit(hex[i * 2 + 1], 16);
            int value = (high << 4) | low;
            if (value > 127)
                value -= 256;
            raw[i] = (byte) value;
        }
        return raw;
    }
}

Related

  1. toBytes(String hex)
  2. toBytes(String hex)
  3. toBytes(String hexStr)
  4. toBytes(String hexStr)
  5. toBytes(String hexString)
  6. toBytes(String name)
  7. toBytes(String s)
  8. toBytes(String s, int len, byte pad)
  9. toBytes(String str, byte[] bytes, int index)