Android Byte Array to Hex Convert toHex(byte[] data)

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

Description

Converts byte data to a Hex-encoded string.

License

Open Source License

Parameter

Parameter Description
data data to hex encode.

Return

hex-encoded string.

Declaration

public static String toHex(byte[] data) 

Method Source Code

//package com.java2s;
/*//w  ww  . j  a va  2 s  .  com
 * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Portions copyright 2006-2009 James Murty. Please see LICENSE.txt
 * for applicable license terms and NOTICE.txt for applicable notices.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import java.util.Locale;

public class Main {
    /**
     * Converts byte data to a Hex-encoded string.
     * 
     * @param data
     *            data to hex encode.
     * 
     * @return hex-encoded string.
     */
    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            String hex = Integer.toHexString(data[i]);
            if (hex.length() == 1) {
                // Append leading zero.
                sb.append("0");
            } else if (hex.length() == 8) {
                // Remove ff prefix from negative numbers.
                hex = hex.substring(6);
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase(Locale.getDefault());
    }
}

Related

  1. byte2hex(byte[] b)
  2. byteArrayToHexString(byte[] b)
  3. bytesToHexString(byte[] bytes)
  4. hex2byte(byte[] b)
  5. toHex(byte[] buf)
  6. toHexString(byte[] b)
  7. toHexString(byte[] buf, int offset, int length)
  8. toHexString(byte[] data)
  9. getHexString(byte[] b)