Java - Convert byte Array To Hexstring

Description

Convert byte Array To Hexstring

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(byteArrayToHexstring(bytes));
    }/* w ww  . j  a v a2  s  .  c  o m*/

    public static String byteArrayToHexstring(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();

        if (bytes.length <= 0 || bytes == null) {
            return null;
        }

        String hv;
        int v = 0;

        for (int i = 0; i < bytes.length; i++) {
            v = bytes[i] & 0xFF;
            hv = Integer.toHexString(v);

            if (hv.length() < 2) {
                hexString.append(0);
            }

            hexString.append(hv);
        }

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

    public static String byteArrayToHexstring(byte[] bytes, int start,
            int end) {
        StringBuilder hexString = new StringBuilder();

        if (bytes.length <= 0 || bytes == null) {
            return null;
        }

        String hv;
        int v = 0;

        for (int i = start; i < end; i++) {
            v = bytes[i] & 0xFF;
            hv = Integer.toHexString(v);

            if (hv.length() < 2) {
                hexString.append(0);
            }

            hexString.append(hv);
        }

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