Java Hex Calculate toHex(byte[] bytes)

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

Description

Converts bytes to hex string

License

Apache License

Parameter

Parameter Description
bytes - incoming bytes or null

Return

string or null

Declaration


public static String toHex(byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*w  w  w.  j  a v a  2  s.  com*/
 * Copyright (C) 2017 Datty.io Authors
 *
 * 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 {
    private final static char[] HEX_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Converts bytes to hex string
     * 
     * @param bytes - incoming bytes or null
     * @return string or null
     */

    public static String toHex(byte[] bytes) {

        if (bytes == null) {
            return null;
        }

        int capacity = bytes.length << 1;

        char[] hexChars = new char[capacity];

        for (int i = 0, j = 0; i != bytes.length; ++i) {

            int v = bytes[i] & 0xFF;
            hexChars[j++] = HEX_ARRAY[v >>> 4];
            hexChars[j++] = HEX_ARRAY[v & 0x0F];

        }

        return new String(hexChars);
    }
}

Related

  1. toHex(byte[] b, int off, int len, String separator)
  2. toHEX(byte[] ba)
  3. toHex(byte[] buffer)
  4. toHex(byte[] buffer)
  5. toHex(byte[] bytes)
  6. toHex(byte[] bytes)
  7. toHex(byte[] bytes)
  8. toHex(byte[] bytes)
  9. toHex(byte[] bytes)