Java Hex Convert To fromHexString(String encoded)

Here you can find the source of fromHexString(String encoded)

Description

Returns a byte array of a given string by converting each character of the string to a number base 16

License

Apache License

Parameter

Parameter Description
encoded the string to convert to a byt string

Return

the encoded byte stream

Declaration

public static byte[] fromHexString(String encoded) 

Method Source Code

//package com.java2s;
/*/*from  w ww  .ja va2s. c  om*/
 * Copyright 2013 Robert von Burg <eitch@eitchnet.ch>
 * 
 * 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 {
    /**
     * Returns a byte array of a given string by converting each character of the string to a number base 16
     * 
     * @param encoded
     *            the string to convert to a byt string
     * 
     * @return the encoded byte stream
     */
    public static byte[] fromHexString(String encoded) {
        if ((encoded.length() % 2) != 0)
            throw new IllegalArgumentException("Input string must contain an even number of characters."); //$NON-NLS-1$

        final byte result[] = new byte[encoded.length() / 2];
        final char enc[] = encoded.toCharArray();
        for (int i = 0; i < enc.length; i += 2) {
            StringBuilder curr = new StringBuilder(2);
            curr.append(enc[i]).append(enc[i + 1]);
            result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16);
        }

        return result;
    }
}

Related

  1. fromHexString(byte abyte0[], int i)
  2. fromHexString(final String hexaString)
  3. fromHexString(final String hexString)
  4. fromHexString(final String s)
  5. fromHexString(final String str)
  6. fromHexString(String encoded)
  7. fromHexString(String hex)
  8. fromHexString(String hex)
  9. fromHexString(String hexString)