Java Hex Convert To fromHexBinary(String s)

Here you can find the source of fromHexBinary(String s)

Description

from Hex Binary

License

Open Source License

Declaration

public static byte[] fromHexBinary(String s) 

Method Source Code

//package com.java2s;
/*//from  ww  w .j  a  v a 2 s . com
 *  PHEX - The pure-java Gnutella-servent.
 *  Copyright (C) 2001 - 2006 Phex Development Group
 *
 *  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, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 *  Created on 23.11.2005
 *  --- CVS Information ---
 *  $Id: ParserUtils.java 3362 2006-03-30 22:27:26Z gregork $
 */

public class Main {
    public static byte[] fromHexBinary(String s) {
        int len = s.length();
        if (len % 2 != 0)
            return null;
        byte out[] = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            int h = hexToBin(s.charAt(i));
            int l = hexToBin(s.charAt(i + 1));
            if (h == -1 || l == -1)
                return null;
            out[i / 2] = (byte) (h * 16 + l);
        }

        return out;
    }

    private static int hexToBin(char ch) {
        if ('0' <= ch && ch <= '9')
            return ch - 48;
        if ('A' <= ch && ch <= 'F')
            return (ch - 65) + 10;
        if ('a' <= ch && ch <= 'f')
            return (ch - 97) + 10;
        else
            return -1;
    }
}

Related

  1. fromHex(String text)
  2. fromHex(String[] data)
  3. fromHex2B(String src)
  4. fromHex8B(String src)
  5. fromHexa(String s)
  6. fromHexChar(char ch)
  7. fromHexChars(char[] chars, int i)
  8. fromHexDigest(String hexDigest)
  9. fromHexDigit(final char c)