Java Array to Hex String arrayToHexString(final byte[] byteArray)

Here you can find the source of arrayToHexString(final byte[] byteArray)

Description

Convert a byte array into hex sequence like [#01 #02 #03]

License

Open Source License

Parameter

Parameter Description
byteArray a byte array to be converted, must not be null

Return

a string represents the array as a hex values

Declaration

public static String arrayToHexString(final byte[] byteArray) 

Method Source Code

//package com.java2s;
/*/*w w  w  .  j  a  v a 2s  .  co m*/
 * Copyright 2012 Igor Maznitsa (http://www.igormaznitsa.com)
 * 
 * This file is part of the JVM to Z80 translator project (hereinafter referred to as J2Z80).
 *
 * J2Z80 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 3 of the License, or
 * (at your option) any later version.
 *
 * J2Z80 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 J2Z80.  If not, see <http://www.gnu.org/licenses/>. 
 */

public class Main {
    /**
     * Convert a byte array into hex sequence like [#01 #02 #03]
     * @param byteArray a byte array to be converted, must not be null 
     * @return a string represents the array as a hex values
     */
    public static String arrayToHexString(final byte[] byteArray) {
        final StringBuilder result = new StringBuilder();
        result.append('[');
        boolean space = false;
        for (final byte b : byteArray) {
            if (space) {
                result.append(' ');
            } else {
                space = true;
            }

            final String byteAsHex = Integer.toHexString(b & 0xFF).toUpperCase();

            result.append('#');
            if (byteAsHex.length() == 1) {
                result.append('0');
            }
            result.append(byteAsHex);
        }
        result.append(']');

        return result.toString();
    }
}

Related

  1. arrayToHexString(byte[] array)
  2. arraytohexstring(byte[] bytes)