Java Hex Calculate toHex(byte in[])

Here you can find the source of toHex(byte in[])

Description

Convert a byte[] array to a readable string format.

License

Apache License

Parameter

Parameter Description
in byte[] buffer to convert to string format

Return

result String buffer in String format

Declaration

public static String toHex(byte in[]) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from  ww  w. j  ava 2s.co m
     * Convert a byte[] array to a readable string format.
     * @return result String buffer in String format 
     * @param in byte[] buffer to convert to string format
     */
    public static String toHex(byte in[]) {
        byte ch = 0x00;
        int i = 0;
        if (in == null || in.length <= 0)
            return null;

        String pseudo[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8",
                "9", "A", "B", "C", "D", "E", "F" };
        StringBuffer out = new StringBuffer(in.length * 2);

        while (i < in.length) {
            ch = (byte) (in[i] & 0xF0); // Strip off high nibble
            ch = (byte) (ch >>> 4); // shift the bits down
            ch = (byte) (ch & 0x0F);
            out.append(pseudo[(int) ch]); // convert the nibble to a String Character 
            ch = (byte) (in[i] & 0x0F); // Strip off low nibble 
            out.append(pseudo[(int) ch]); // convert the nibble to a String Character 
            i++;
        }
        return out.toString();
    }

    /** 
     * Converts a byte to a readable string.
     * @return result String byte in hex format 
     * @param b byte Byte to convert to string (hex) format
     */
    public static String toHex(byte b) {
        byte[] barr = new byte[1];
        barr[0] = b;
        return toHex(barr);
    }
}

Related

  1. toHex(byte bytes[])
  2. toHex(byte data[])
  3. toHex(byte hash[])
  4. toHex(byte in)
  5. toHex(byte in[])
  6. toHex(byte input[])
  7. toHex(byte lowByte)
  8. toHex(byte n)
  9. toHex(byte one)