Java Byte Array Create toBytes(String hex)

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

Description

Convert a hex string to a byte[].

License

Open Source License

Parameter

Parameter Description
hex a parameter

Return

byte array

Declaration

public static byte[] toBytes(String hex) 

Method Source Code

//package com.java2s;
/*//  w  ww  . ja v  a  2s  .  c  o m
************************************************************************
*******************  CANADIAN ASTRONOMY DATA CENTRE  *******************
**************  CENTRE CANADIEN DE DONN?ES ASTRONOMIQUES  **************
*
*  (c) 2009.                            (c) 2009.
*  Government of Canada                 Gouvernement du Canada
*  National Research Council            Conseil national de recherches
*  Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
*  All rights reserved                  Tous droits r?serv?s
*
*  NRC disclaims any warranties,        Le CNRC d?nie toute garantie
*  expressed, implied, or               ?nonc?e, implicite ou l?gale,
*  statutory, of any kind with          de quelque nature que ce
*  respect to the software,             soit, concernant le logiciel,
*  including without limitation         y compris sans restriction
*  any warranty of merchantability      toute garantie de valeur
*  or fitness for a particular          marchande ou de pertinence
*  purpose. NRC shall not be            pour un usage particulier.
*  liable in any event for any          Le CNRC ne pourra en aucun cas
*  damages, whether direct or           ?tre tenu responsable de tout
*  indirect, special or general,        dommage, direct ou indirect,
*  consequential or incidental,         particulier ou g?n?ral,
*  arising from the use of the          accessoire ou fortuit, r?sultant
*  software.  Neither the name          de l'utilisation du logiciel. Ni
*  of the National Research             le nom du Conseil National de
*  Council of Canada nor the            Recherches du Canada ni les noms
*  names of its contributors may        de ses  participants ne peuvent
*  be used to endorse or promote        ?tre utilis?s pour approuver ou
*  products derived from this           promouvoir les produits d?riv?s
*  software without specific prior      de ce logiciel sans autorisation
*  written permission.                  pr?alable et particuli?re
*                                       par ?crit.
*
*  This file is part of the             Ce fichier fait partie du projet
*  OpenCADC project.                    OpenCADC.
*
*  OpenCADC is free software:           OpenCADC est un logiciel libre ;
*  you can redistribute it and/or       vous pouvez le redistribuer ou le
*  modify it under the terms of         modifier suivant les termes de
*  the GNU Affero General Public        la ?GNU Affero General Public
*  License as published by the          License?? telle que publi?e
*  Free Software Foundation,            par la Free Software Foundation
*  either version 3 of the              : soit la version 3 de cette
*  License, or (at your option)         licence, soit (? votre gr?)
*  any later version.                   toute version ult?rieure.
*
*  OpenCADC is distributed in the       OpenCADC est distribu?
*  hope that it will be useful,         dans l?espoir qu?il vous
*  but WITHOUT ANY WARRANTY;            sera utile, mais SANS AUCUNE
*  without even the implied             GARANTIE : sans m?me la garantie
*  warranty of MERCHANTABILITY          implicite de COMMERCIALISABILIT?
*  or FITNESS FOR A PARTICULAR          ni d?AD?QUATION ? UN OBJECTIF
*  PURPOSE.  See the GNU Affero         PARTICULIER. Consultez la Licence
*  General Public License for           G?n?rale Publique GNU Affero
*  more details.                        pour plus de d?tails.
*
*  You should have received             Vous devriez avoir re?u une
*  a copy of the GNU Affero             copie de la Licence G?n?rale
*  General Public License along         Publique GNU Affero avec
*  with OpenCADC.  If not, see          OpenCADC ; si ce n?est
*  <http://www.gnu.org/licenses/>.      pas le cas, consultez :
*                                       <http://www.gnu.org/licenses/>.
*
*  $Revision: 4 $
*
************************************************************************
*/

public class Main {
    private static byte[] correspondingNibble = new byte['f' + 1];

    /**
     * Put byte into an array of length == 1.
      *
      * @param n
      * @return a minimum-sized byte[] containing n
     */
    public static byte[] toBytes(byte n) {
        return new byte[] { n };
    }

    /**
     * Encode a short as bytes and put into array of length == 2.
      *
      * @param n
      * @return a minimum-sized byte[] containing n
     */
    public static byte[] toBytes(short n) {
        byte[] ret = new byte[2];
        ret[0] = (byte) (n >> 8);
        ret[1] = (byte) ((n << 8) >> 8);
        //ret[1] = (byte) (n & 0x00ff );
        return ret;
    }

    /**
     * Encode a int as bytes and put into array of length == 4.
      *
      * @param n
      * @return a minimum-sized byte[] containing n
     */
    public static byte[] toBytes(int n) {
        byte[] ret = new byte[4];
        ret[0] = (byte) (n >> 24);
        ret[1] = (byte) ((n << 8) >> 24);
        ret[2] = (byte) ((n << 16) >> 24);
        ret[3] = (byte) ((n << 24) >> 24);
        return ret;
    }

    /**
     * Encode a long as bytes and put into array of length == 8.
      *
      * @param n
      * @return a minimum-sized byte[] containing n
     */
    public static byte[] toBytes(long n) {
        byte[] ret = new byte[8];
        ret[0] = (byte) (n >> 56);
        ret[1] = (byte) ((n << 8) >> 56);
        ret[2] = (byte) ((n << 16) >> 56);
        ret[3] = (byte) ((n << 24) >> 56);
        ret[4] = (byte) ((n << 32) >> 56);
        ret[5] = (byte) ((n << 40) >> 56);
        ret[6] = (byte) ((n << 48) >> 56);
        ret[7] = (byte) ((n << 56) >> 56);
        return ret;
    }

    /**
     * Convert a hex string to a byte[].
     *
     * @param hex
     * @return byte array
     */
    public static byte[] toBytes(String hex) {
        if (hex == null || hex.length() % 2 != 0)
            throw new IllegalArgumentException();
        byte[] ret = new byte[hex.length() / 2];

        //for (int i=0; i<ret.length; i++)
        //    ret[i] = HexUtil.toByte(hex.substring(i*2, 2));

        for (int i = 0, j = 0; i < hex.length(); i += 2, j++) {
            int high = charToNibble(hex.charAt(i));
            int low = charToNibble(hex.charAt(i + 1));
            // You can store either unsigned 0..255 or signed -128..127 bytes in a byte type.
            ret[j] = (byte) ((high << 4) | low);
        }
        return ret;
    }

    private static int charToNibble(char c) {
        if (c > 'f') {
            throw new IllegalArgumentException("Invalid hex character: " + c);
        }
        int nibble = correspondingNibble[c];
        if (nibble < 0) {
            throw new IllegalArgumentException("Invalid hex character: " + c);
        }
        return nibble;
    }
}

Related

  1. toBytes(short value)
  2. toBytes(short value)
  3. toBytes(String hex)
  4. toBytes(String hex)
  5. toBytes(String hex)
  6. toBytes(String hex)
  7. toBytes(String hex)
  8. toBytes(String hexStr)
  9. toBytes(String hexStr)