Java Hex Calculate toHexString(byte[] bytes)

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

Description

Converts a byte array to a hex String by HNF order.

License

Apache License

Parameter

Parameter Description
bytes a byte array

Return

hex String

Declaration

public static String toHexString(byte[] bytes) 

Method Source Code

//package com.java2s;
/**/*from w w  w  .java 2s.  com*/
 *
 * @author Wei-Ming Wu
 *
 *
 * Copyright 2013 Wei-Ming Wu
 *
 * 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 {
    /**
     * Converts a byte array to a hex String by HNF order.
     * 
     * @param bytes
     *          a byte array
     * @return hex String
     */
    public static String toHexString(byte[] bytes) {
        return toHexString(bytes, true);
    }

    /**
     * Converts a byte array to a hex String.
     * 
     * @param bytes
     *          a byte array
     * @param isHNF
     *          true if HNF(high nibble first), false if LNF(low nibble first)
     * @return hex String
     */
    public static String toHexString(byte[] bytes, boolean isHNF) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = String.format("%2s", Integer.toHexString(b & 0xFF)).replace(' ', '0');
            if (isHNF)
                sb.append(hex);
            else
                sb.append(new StringBuilder(hex).reverse());
        }
        return sb.toString();
    }

    /**
     * Reverses a byte array in place.
     * 
     * @param bytes
     *          to be reversed
     */
    public static void reverse(byte[] bytes) {
        for (int i = 0; i < bytes.length / 2; i++) {
            byte temp = bytes[i];
            bytes[i] = bytes[bytes.length - 1 - i];
            bytes[bytes.length - 1 - i] = temp;
        }
    }
}

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)
  9. toHexString(byte[] bytes)