Java Byte Array to Hex byteToTwoHexString(final byte data)

Here you can find the source of byteToTwoHexString(final byte data)

Description

Convert a byte to a String of two Hex characters, with leading zero.

License

Open Source License

Parameter

Parameter Description
data a parameter

Return

String

Declaration


public static String byteToTwoHexString(final byte data) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by

public class Main {
    /***********************************************************************************************
     * Convert a byte to a String of two Hex characters, with leading zero. 00...FF
     * Always return upper case./*from www .j  av  a2 s.c om*/
     *
     * @param data
     *
     * @return String
     */

    public static String byteToTwoHexString(final byte data) {
        final StringBuffer buffer;
        final String strHex;

        buffer = new StringBuffer();

        // Returns a string representation of the *integer* argument as an unsigned integer in base 16
        strHex = Integer.toHexString(data & 0xFF);

        // Replace leading zeroes
        if (strHex.length() == 0) {
            // Not needed?
            buffer.append("00");
        } else if (strHex.length() == 1) {
            buffer.append("0");
            buffer.append(strHex);
        } else {
            // We must remove any leading 'FF's caused by sign extension...
            buffer.append(strHex.substring(0, 2));
        }

        return (buffer.toString().toUpperCase());
    }
}

Related

  1. byteToHex(int val)
  2. byteToHex(int val, StringBuffer sb)
  3. byteToHexDisplayString(byte[] b)
  4. byteToHexWord(byte in)
  5. byteToLowerHex(final byte b)