Java Hex Convert To fromHex(final String hex)

Here you can find the source of fromHex(final String hex)

Description

Convert a string of hex to bytes.

License

Apache License

Parameter

Parameter Description
hex The hex string.

Return

The bytes.

Declaration

public static final byte[] fromHex(final String hex) 

Method Source Code

//package com.java2s;
/*//from  ww w  . j  ava2  s.c  o  m
 * Copyright 2010,2014 Attribyte, LLC
 * 
 * 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 {
    /**
     * Indicates characters outside the hex alphabet.
     * Accepts both upper and lower-case.
     */
    private static final int INVALID_HEX_DIGIT = -1;
    private static final int[] hexVals = new int[256];

    /**
     * Convert a string of hex to bytes.
     * @param hex The hex string.
     * @return The bytes.
     */
    public static final byte[] fromHex(final String hex) {

        char[] ch = hex.toCharArray();

        if (ch.length % 2 != 0) {
            throw new UnsupportedOperationException("The hex string must contain an even number of digits");
        }

        byte[] b = new byte[ch.length / 2];
        char ch0, ch1;

        try {

            for (int i = 0; i < ch.length; i += 2) {
                ch0 = ch[i];
                ch1 = ch[i + 1];

                int v1 = hexVals[ch0];
                if (v1 == INVALID_HEX_DIGIT) {
                    throw new UnsupportedOperationException("The character, '" + ch0 + "' is not a hex digit");
                }

                int v2 = hexVals[ch1];
                if (v2 == INVALID_HEX_DIGIT) {
                    throw new UnsupportedOperationException("The character, '" + ch1 + "' is not a hex digit");
                }

                b[i / 2] = (byte) ((v1 << 4) | v2);
            }

            return b;

        } catch (IndexOutOfBoundsException e) {
            throw new UnsupportedOperationException("The hex string contains an invalid hex digit");
        }
    }
}

Related

  1. fromHex(char c)
  2. fromHex(char c)
  3. fromHex(char hi, char lo)
  4. fromHex(CharSequence cs)
  5. fromHex(final CharSequence s)
  6. fromHex(final String hex)
  7. fromHex(final String hexValue)
  8. fromHex(final String s)
  9. fromHex(final String string, final int offset, final int count)