create a hexidecimal string from a byte-array preappend with 0x token - Java java.lang

Java examples for java.lang:String Hex

Description

create a hexidecimal string from a byte-array preappend with 0x token

Demo Code


public class Main{
    public static void main(String[] argv){
        byte[] byteArray = new byte[]{34,35,36,37,37,37,67,68,69};
        System.out.println(stringFromBytesWithToken(byteArray));
    }/*from  w  w  w .j  a  v a2  s . c  om*/
    private static final short BYTE_SHIFT = 8;
    private static final short LOW_BYTE_MASK = (short) ((short) (1 << BYTE_SHIFT) - 1);
    private static final short HIGH_NIBBLE_MASK = (short) 0xf0;
    private static final String HEX_TOKEN = "0x";
    /**
     * Method stringFromBytesWithToken
     * Description: create a hexidecimal string from a byte-array
     * preappend with 0x token
     * 
     * @param byteArray
     * @return String
     */
    public static String stringFromBytesWithToken(byte[] byteArray) {
        return new String(HEX_TOKEN + stringFromBytes(byteArray));
    }
    /**
     * Method stringFromBytes
     * Description: create a hexidecimal string from a byte-array
     * 
     * @param byteArray
     * @return String
     */

    public static String stringFromBytes(byte[] byteArray) {

        StringBuffer str = new StringBuffer("");

        for (int i = 0; i < byteArray.length; i++) {
            if ((int) (byteArray[i] & HIGH_NIBBLE_MASK) > 0) {
                str.append(Integer.toHexString((int) byteArray[i]
                        & LOW_BYTE_MASK));
            } else {
                str.append("0"
                        + Integer.toHexString((int) byteArray[i]
                                & LOW_BYTE_MASK));
            }
        }

        return str.toString();
    }
}

Related Tutorials