Dumps a byte array into a hex string (e.g CB 2A FF ...). - Java java.lang

Java examples for java.lang:byte Array to int

Description

Dumps a byte array into a hex string (e.g CB 2A FF ...).

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(dumpByteArray(data));
    }//  w  w w. j a  va 2 s .c o  m

    /**
     * Dumps a byte array into a hex string (e.g CB 2A FF ...).
     *
     * @param data the byte array
     * @return a hex string
     */
    public static String dumpByteArray(byte[] data) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            s.append(String.format("%02X", byteToInt(data[i]))).append(" ");
        }
        return s.toString();
    }

    /**
     * Dumps a int array into a hex string (e.g CB 2A FF ...).
     *
     * @param data the byte array
     * @return a hex string
     */
    public static String dumpByteArray(int[] data) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            s.append(String.format("%02X", data[i])).append(" ");
        }
        return s.toString();
    }

    /**
     * Converts a unsigned byte to an signed int value.
     *
     * @param b a byte
     * @return the byte as int value
     */
    public static int byteToInt(byte b) {
        return (int) b & 0x00000000FF;
    }
}

Related Tutorials