Java Array to Hex String arrayToHexString(byte[] array)

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

Description

Helper method to convert a byte[] array (such as a MsgId) to a hex string

License

Open Source License

Parameter

Parameter Description
array a parameter

Return

hex string

Declaration

public static String arrayToHexString(byte[] array) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2014 IBM Corp.//from   w w w .  j  a v a  2  s.  com
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution. 
 *
 * The Eclipse Public License is available at 
 *    http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at 
 *   http://www.eclipse.org/org/documents/edl-v10.php.
 *
 *******************************************************************************/

public class Main {
    /**
     * Helper method to convert a byte[] array (such as a MsgId) to a hex string
     *
     * @param array
     * @return hex string
     */
    public static String arrayToHexString(byte[] array) {
        return arrayToHexString(array, 0, array.length);
    }

    /**
     * Helper method to convert a byte[] array (such as a MsgId) to a hex string
     *
     * @param array
     * @param offset 
     * @param limit 
     * @return hex string
     */
    public static String arrayToHexString(byte[] array, int offset, int limit) {
        String retVal;
        if (array != null) {
            StringBuffer hexString = new StringBuffer(array.length);
            int hexVal;
            char hexChar;
            int length = Math.min(limit, array.length);
            for (int i = offset; i < length; i++) {
                hexVal = (array[i] & 0xF0) >> 4;
                hexChar = (char) ((hexVal > 9) ? ('A' + (hexVal - 10)) : ('0' + hexVal));
                hexString.append(hexChar);
                hexVal = array[i] & 0x0F;
                hexChar = (char) ((hexVal > 9) ? ('A' + (hexVal - 10)) : ('0' + hexVal));
                hexString.append(hexChar);
            }
            retVal = hexString.toString();
        } else {
            retVal = "<null>";
        }
        return retVal;
    }
}

Related

  1. arraytohexstring(byte[] bytes)
  2. arrayToHexString(final byte[] byteArray)