Java Hex Calculate toHexString(byte[] bytes)

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

Description

Convert a byte array into a hexadecimal String representation.

License

Open Source License

Parameter

Parameter Description
bytes array of bytes to convert

Return

hexadecimal representation

Declaration

public static String toHexString(byte[] bytes) 

Method Source Code

//package com.java2s;
/**/*from   ww  w .  j  a va2  s  .  c  o  m*/
 *  Copyright (C) 2004-2007 Orbeon, Inc.
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the
 *  GNU Lesser General Public License as published by the Free Software Foundation; either version
 *  2.1 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Lesser General Public License for more details.
 *
 *  The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
 */

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

    /**
     * Convert a byte array into a hexadecimal String representation.
     *
     * @param bytes  array of bytes to convert
     * @return       hexadecimal representation
     */
    public static String toHexString(byte[] bytes) {
        final StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            sb.append(digits[(bytes[i] >> 4) & 0x0f]);
            sb.append(digits[bytes[i] & 0x0f]);
        }
        return sb.toString();
    }

    /**
     * Convert a byte into a hexadecimal String representation.
     *
     * @param b      byte to convert
     * @return       hexadecimal representation
     */
    public static String toHexString(byte b) {
        final StringBuilder sb = new StringBuilder(2);
        sb.append(digits[(b >> 4) & 0x0f]);
        sb.append(digits[b & 0x0f]);
        return sb.toString();
    }
}

Related

  1. toHexString(byte[] bytes)
  2. toHexString(byte[] bytes)
  3. toHexString(byte[] bytes)
  4. toHexString(byte[] bytes)
  5. toHexString(byte[] bytes)
  6. toHexString(byte[] bytes)
  7. toHexString(byte[] bytes)
  8. toHexString(byte[] bytes, boolean addPrefix)
  9. toHexString(byte[] bytes, int offset, int len, int max)