Prints out a pretty hex version of a byte array. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Prints out a pretty hex version of a byte array.

Demo Code


//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 };
        bytePrint(bytes);/*from   w ww  . ja v a2 s  .co m*/
    }

    /**
     * Prints out a pretty hex version of a byte array.  The
     * length of the line of text is specified based on the
     * lineLen.
     *  
     * @param bytes
     * @param lineLen
     */

    public final static void bytePrint(byte[] bytes, int lineLen) {

        if (bytes.length < lineLen) {

            for (int i = 0; i < bytes.length; i++) {
                String s = Integer.toHexString(bytes[i] & 0x00ff);
                if (s.length() < 2)
                    s = "0" + s;
                System.out.print(s + " ");
            }

            System.out.println();

        } else {

            int count = 0;

            while (count < bytes.length) {
                System.out.println("count = " + count);
                for (int i = count; i < count + lineLen; i++) {
                    String s = Integer.toHexString(bytes[i] & 0x00ff);
                    if (s.length() < 2)
                        s = "0" + s;
                    System.out.print(s + " ");
                }
                count += lineLen;
                System.out.println();
            }

        }

    }

    /**
     * Conveniently print bytes in 8 columns.
     * 
     * @param bytes
     */

    public final static void bytePrint(byte[] bytes) {
        bytePrint(bytes, 8);
    }
}

Related Tutorials