Java Hex Convert To fromHex(String hex)

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

Description

Decodes a string of hex octets to a byte array.

License

Open Source License

Parameter

Parameter Description
hex a byte array

Return

decoded byte array

Declaration

public static byte[] fromHex(String hex) 

Method Source Code

//package com.java2s;
/*//  ww  w  .  j a v a2 s.c  o  m
 * This file is part of M.O.R.F.
 *                      <https://github.com/HeXLaB/M.O.R.F.>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (c) 2013-2014
 *               HeXLaB Team
 *                           All rights reserved
 */

public class Main {
    /**
     * Decodes a string of hex octets to a byte array.
     *
     * @param hex
     *     a byte array
     *
     * @return decoded byte array
     */
    public static byte[] fromHex(String hex) {
        if (hex == null) {
            return null;
        }
        hex = hex.replace(" ", "");
        if (hex.length() % 2 == 1) {
            return null;
        }

        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            String byte_ = hex.substring(i * 2, (i + 1) * 2);
            bytes[i] = (byte) (Integer.parseInt(byte_, 16) & 0xFF);
        }
        return bytes;
    }
}

Related

  1. fromHex(final String string, final int offset, final int count)
  2. fromHex(String bytesString)
  3. fromHex(String encoded)
  4. fromHex(String hex)
  5. fromHex(String hex)
  6. fromHex(String hex)
  7. fromHex(String hex)
  8. fromHex(String hex)
  9. fromHex(String hex)