Java Byte Array Create toBytes(final String str)

Here you can find the source of toBytes(final String str)

Description

Converts a hex-encoded string to bytes.

License

Apache License

Parameter

Parameter Description
str the string to decode.

Exception

Parameter Description
IllegalArgumentException if <tt>str.length() % 2 != 0</tt> or character not in <tt>[0-9a-fA-F]</tt>.
NullPointerException if <tt>str</tt> is <tt>null</tt>.

Return

hex-decoded bytes.

Declaration

public static byte[] toBytes(final String str) 

Method Source Code

//package com.java2s;
/*//w w  w. j a v  a2 s .  c  o m
 * Copyright 2007  T-Rank AS
 * 
 * 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-encoded string to bytes.
     * 
     * @param str the string to decode.
     * 
     * @return hex-decoded bytes.
     * 
     * @throws IllegalArgumentException if <tt>str.length() % 2 != 0</tt> or character not in <tt>[0-9a-fA-F]</tt>.
     * @throws NullPointerException if <tt>str</tt> is <tt>null</tt>.
     */
    public static byte[] toBytes(final String str) {
        final int len = str.length();
        if (len % 2 != 0) {
            throw new IllegalArgumentException("String '" + str + "'.length() % 2 != 0");
        }
        final byte[] buf = new byte[len / 2];
        int idx = 0;
        for (int i = 0; i < buf.length; i++) {
            final int b1 = charToOctet(str.charAt(idx++));
            final int b2 = charToOctet(str.charAt(idx++));
            if (b1 < 0 || b2 < 0 || b1 > 0xf || b2 > 0xf) {
                throw new IllegalArgumentException("String '" + str + "' is not hex-encoded");
            }
            buf[i] = (byte) ((b1 << 4) | b2);
        }
        return buf;
    }

    private static int charToOctet(char c) {
        if (c > '9') {
            if (c > 'F') {
                return c - 'a' + 10;
            }
            return c - 'A' + 10;
        }
        return c - '0';
    }
}

Related

  1. toBytes(char[] chars)
  2. toBytes(final byte[] s, final int off, final int len)
  3. toBytes(final long n)
  4. toBytes(final long val)
  5. toBytes(final String hexaString)
  6. toBytes(final String text)
  7. toBytes(int data)
  8. toBytes(int data)
  9. toBytes(int i)