Java Hex Calculate toHex(final byte[] ba)

Here you can find the source of toHex(final byte[] ba)

Description

Converts a byte array to a string of hexadecimal characters.

License

Open Source License

Parameter

Parameter Description
ba the bytearray to be converted

Return

ba converted to a hexstring

Declaration

public static String toHex(final byte[] ba) 

Method Source Code

//package com.java2s;
/*//from w  w w .  j a v a2  s  . c  o  m
 *     ByteUtils.java
 *     Copyright (C) 2008  Asger Blekinge-Rasmussen
 * 
 *     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 Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

public class Main {
    private static final byte MAGIC_INTEGER_4 = 4;
    private static final byte MAGIC_INTEGER_OxOF = 0x0f;

    /**
     * Converts a byte array to a string of hexadecimal characters.
     * @param ba the bytearray to be converted
     * @return ba converted to a hexstring
     */
    public static String toHex(final byte[] ba) {
        char[] hexdigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

        StringBuffer sb = new StringBuffer("");
        int ba_len = ba.length;

        for (int i = 0; i < ba_len; i++) {
            sb.append(hexdigit[(ba[i] >> MAGIC_INTEGER_4) & MAGIC_INTEGER_OxOF]);
            sb.append(hexdigit[ba[i] & MAGIC_INTEGER_OxOF]);
        }
        return sb.toString();
    }
}

Related

  1. toHex(byte[] value)
  2. toHex(char c)
  3. toHex(final byte b)
  4. toHex(final byte b)
  5. toHex(final byte... bin)
  6. toHex(final byte[] ba)
  7. toHex(final byte[] bytes)
  8. toHex(final byte[] bytes)
  9. toHex(final byte[] bytes)