Java Hex Calculate toHex(byte[] bytes)

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

Description

Converts the specified array of bytes to a hex string.

License

Open Source License

Parameter

Parameter Description
bytes The array of bytes to convert to a string.

Return

The hexadecimal representation of bytes.

Declaration

public static String toHex(byte[] bytes) 

Method Source Code

//package com.java2s;
/*// w w  w  .  j ava2s.  c o m
 * Copyright (c) 2008 Bradley W. Kimmel
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

public class Main {
    /** The hexadecimal digits. */
    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Converts the specified byte value to a two digit hex string.
     * @param b The <code>byte</code> value to convert to a string.
     * @return The two digit hexadecimal representation of <code>b</code>.
     */
    public static String toHex(byte b) {
        final char[] string = { hexDigits[(b >> 4) & 0x0f], hexDigits[b & 0x0f] };
        return new String(string);
    }

    /**
     * Converts the specified array of bytes to a hex string.
     * @param bytes The array of bytes to convert to a string.
     * @return The hexadecimal representation of <code>bytes</code>.
     */
    public static String toHex(byte[] bytes) {
        final char[] string = new char[2 * bytes.length];
        int i = 0;
        for (byte b : bytes) {
            string[i++] = hexDigits[(b >> 4) & 0x0f];
            string[i++] = hexDigits[b & 0x0f];
        }
        return new String(string);
    }
}

Related

  1. toHex(byte[] buffer)
  2. toHex(byte[] bytes)
  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)