byte to HEX String using shifting - Java java.lang

Java examples for java.lang:Hex

Description

byte to HEX String using shifting

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(byte2HexString(b));
    }/*from w w  w.j  a v  a 2 s. c om*/

    private static String byte2HexString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        char[] hex = new char[] { '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        if (b == null)
            return "null";
        int offset = 0;
        int len = b.length;

        int end = offset + len;
        if (end > b.length)
            end = b.length;
        sb.delete(0, sb.length());
        for (int i = offset; i < end; i++) {
            sb.append(hex[(b[i] & 0xF0) >>> 4]).append(hex[b[i] & 0xF]);
        }
        return sb.toString();
    }
}

Related Tutorials