Java Hex Convert To fromHexToBytes(String hex)

Here you can find the source of fromHexToBytes(String hex)

Description

from Hex To Bytes

License

Open Source License

Declaration

public static byte[] fromHexToBytes(String hex) 

Method Source Code

//package com.java2s;
/*//  ww w  . ja  v a 2 s.  c o m
 * Mentawai Web Framework http://mentawai.lohis.com.br/
 * Copyright (C) 2005  Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

public class Main {
    public static byte[] fromHexToBytes(String hex) {

        int x = hex.length() / 2;

        byte[] b = new byte[x];

        int index = 0;

        for (int i = 0; i < hex.length(); i += 2) {

            byte b1 = toByte(hex.charAt(i));

            byte b2 = toByte(hex.charAt(i + 1));

            b[index++] = (byte) ((b1 << 4) + b2);
        }

        return b;
    }

    private static byte toByte(char hex) {

        switch (hex) {

        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'A':
        case 'a':
            return 10;
        case 'B':
        case 'b':
            return 11;
        case 'C':
        case 'c':
            return 12;
        case 'D':
        case 'd':
            return 13;
        case 'E':
        case 'e':
            return 14;
        case 'F':
        case 'f':
            return 15;

        default:
            throw new IllegalArgumentException("Not a valid hex digit: " + hex);
        }
    }
}

Related

  1. fromHexString(String s)
  2. fromHexString(String s, int offset, int length)
  3. fromHexString(String str)
  4. fromHexString(String text)
  5. fromHexString(String value)