Convert byte array to HEX format. - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Convert byte array to HEX format.

Demo Code

/*//from   ww  w.  j  a v  a2  s  .  co  m
 * WireSpider
 *
 * Copyright (c) 2015 kazyx
 *
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHex(bytes));
    }

    private static final char[] HEX_SOURCE = { '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    /**
     * Convert byte array to HEX format.
     *
     * @param bytes Source byte array
     * @return HEX format.
     */
    public static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        sb.append("0x");
        for (byte b : bytes) {
            int v = b & 0xFF;
            sb.append(HEX_SOURCE[v >>> 4]).append(HEX_SOURCE[v & 0x0F]);
        }
        return sb.toString();
    }
}

Related Tutorials