Java Byte Array Create toByteArray(String hexString)

Here you can find the source of toByteArray(String hexString)

Description

toHexString - generate a byte array representation of the specified string

License

Open Source License

Parameter

Parameter Description
hexString The string to convert

Return

The byte array representation of the given string

Declaration

protected static byte[] toByteArray(String hexString) 

Method Source Code

//package com.java2s;
/*/*from w w w  .  j  ava  2  s  . co  m*/
 collabREate Utils
 Copyright (C) 2008 Chris Eagle <cseagle at gmail d0t com>
 Copyright (C) 2008 Tim Vidas <tvidas at gmail d0t com>

 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
 */

public class Main {
    /**
     * toHexString - generate a byte array representation of the specified
     *               string
     * @param hexString The string to convert
     * @return The byte array representation of the given string
     */
    protected static byte[] toByteArray(String hexString) {
        if ((hexString.length() % 2) == 1) {
            //invalid hex string
            return null;
        }
        try {
            int idx = 0;
            byte result[] = new byte[hexString.length() / 2];
            for (int i = 0; i < hexString.length(); i += 2) {
                String val = hexString.substring(i, i + 2);
                int b = Integer.parseInt(val, 16);
                result[idx++] = (byte) b;
            }
            return result;
        } catch (Exception ex) {
            return null;
        }
    }
}

Related

  1. toByteArray(String hex)
  2. toByteArray(String hex)
  3. toByteArray(String hexStr)
  4. toByteArray(String hexString)
  5. toByteArray(String hexString)
  6. toByteArray(String map)
  7. toByteArray(String s)
  8. toByteArray(String source)
  9. toByteArray(String str)