Java Hex Convert To fromHexString(String encoded)

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

Description

from Hex String

License

Apache License

Declaration

public static byte[] fromHexString(String encoded) 

Method Source Code

//package com.java2s;
/*//www  .j  a v  a2s. c o  m
 * Copyright 2010 sasc
 *
 * 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 {
    public static byte[] fromHexString(String encoded) {
        encoded = removeSpaces(encoded);
        if (encoded.length() == 0) {
            return new byte[0];
        }
        if ((encoded.length() % 2) != 0) {
            throw new IllegalArgumentException(
                    "Input string must contain an even number of characters: " + encoded);
        }
        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;
    }

    public static String removeSpaces(String s) {
        return s.replaceAll(" ", "");
    }
}

Related

  1. fromHexString(final String hexaString)
  2. fromHexString(final String hexString)
  3. fromHexString(final String s)
  4. fromHexString(final String str)
  5. fromHexString(String encoded)
  6. fromHexString(String hex)
  7. fromHexString(String hex)
  8. fromHexString(String hexString)
  9. fromHexString(String hexString)