Java Hex Calculate toHex(final byte[] bytes)

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

Description

Converts bytes to a string of hex.

License

Apache License

Parameter

Parameter Description
bytes The bytes

Return

The bytes as a hex string.

Declaration

public static final String toHex(final byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*from www.  ja v  a 2s . c o  m*/
 * Copyright 2010,2014 Attribyte, LLC
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and limitations under the License.  
 * 
 */

public class Main {
    /**
     * Upper-case hex alphabet.
     */
    private static final char[] hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F' };
    private static final int lMask = 0x0F;
    private static final int hMask = lMask << 4;

    /**
     * Converts bytes to a string of hex.
     * @param bytes The bytes
     * @return The bytes as a hex string.
     */
    public static final String toHex(final byte[] bytes) {

        char[] buf = new char[bytes.length * 2];
        int pos = 0;
        for (final byte aByte : bytes) {
            int index = (aByte & hMask) >> 4;
            char currChar = hexChars[index];
            buf[pos++] = currChar;
            index = (aByte & lMask);
            currChar = hexChars[index];
            buf[pos++] = currChar;
        }

        return new String(buf);
    }
}

Related

  1. toHex(final byte b)
  2. toHex(final byte... bin)
  3. toHex(final byte[] ba)
  4. toHex(final byte[] ba)
  5. toHex(final byte[] bytes)
  6. toHex(final byte[] bytes)
  7. toHex(final byte[] bytes)
  8. toHex(final byte[] bytes)
  9. toHex(final byte[] bytes)