Android String to Byte Array Convert 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  a2 s .c om
 * 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) {
        // take out spaces
        hexString = hexString.replace(" ", "");
        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. String2Byte(String hexString)
  2. StringToByteArray(String input)
  3. StrToBcdBytes(String s)
  4. Str2Bcd(String asc)
  5. toBytes(String digits, int radix)
  6. toBytes(String hexString)
  7. toBytes(String s)
  8. stringToByteString(String string)