Java Hex Calculate toHex(byte[] bytes)

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

Description

Converts a byte array into a simple hexadecimal character string.

License

Apache License

Parameter

Parameter Description
bytes The bytes to convert to hexadecimal.

Return

A new string consisting of hexadecimal characters.

Declaration

public static String toHex(byte[] bytes) 

Method Source Code

//package com.java2s;
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *

public class Main {
    private final static char[] HEX = "0123456789ABCDEF".toCharArray();

    /**/* w w w. j  a v  a 2 s  . co  m*/
     * Converts the specified number into a 4 hexadecimal characters.
     *
     * @param num The number to convert to hex.
     * @return A <code><jk>char</jk>[4]</code> containing the specified characters.
     */
    public static final char[] toHex(int num) {
        char[] n = new char[4];
        int a = num % 16;
        n[3] = (char) (a > 9 ? 'A' + a - 10 : '0' + a);
        int base = 16;
        for (int i = 1; i < 4; i++) {
            a = (num / base) % 16;
            base <<= 4;
            n[3 - i] = (char) (a > 9 ? 'A' + a - 10 : '0' + a);
        }
        return n;
    }

    /**
     * Converts a byte array into a simple hexadecimal character string.
     *
     * @param bytes The bytes to convert to hexadecimal.
     * @return A new string consisting of hexadecimal characters.
     */
    public static String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            sb.append(HEX[v >>> 4]).append(HEX[v & 0x0F]);
        }
        return sb.toString();
    }

    /**
     * Calls {@link #toString()} on the specified object if it's not null.
     *
     * @param o The object to convert to a string.
     * @return The object converted to a string, or <jk>null</jk> if the object was null.
     */
    public static String toString(Object o) {
        return (o == null ? null : o.toString());
    }
}

Related

  1. toHex(byte[] buffer)
  2. toHex(byte[] buffer)
  3. toHex(byte[] bytes)
  4. toHex(byte[] bytes)
  5. toHex(byte[] bytes)
  6. toHex(byte[] bytes)
  7. toHex(byte[] bytes)
  8. toHex(byte[] bytes)
  9. toHex(byte[] bytes)