Java Hex Calculate toHex(byte[] bytes)

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

Description

Byte array to Hex info

License

Apache License

Parameter

Parameter Description
bytes a parameter

Declaration

public static String toHex(byte[] bytes) 

Method Source Code

//package com.java2s;
/*/*from  w ww. j  ava  2s  .  c o m*/
 * Copyright (C) 2011 Prasanta Paul, http://prasanta-paul.blogspot.com
 *
 * 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 static final String[] hexStr = { "A", "B", "C", "D", "E", "F" };

    /**
     * Byte array to Hex info
     * 
     * @param bytes
     * @return
     */
    public static String toHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0)
            return "";
        String hex = "";
        for (int i = 0; i < bytes.length; i++) {
            int num = 0xFF & bytes[i];
            int div = num / 16;
            int rem = num % 16;

            // 0xF9
            if (div > 9) {
                div -= 10;
                hex += " 0x" + hexStr[div];
            } else
                hex += " 0x" + div;

            if (rem > 9) {
                rem -= 10;
                hex += "" + hexStr[rem];
            } else
                hex += "" + rem;
        }
        return hex;
    }
}

Related

  1. toHex(byte[] bytes)
  2. toHex(byte[] bytes)
  3. toHex(byte[] bytes)
  4. toHex(byte[] bytes)
  5. toHex(byte[] bytes)
  6. toHex(byte[] bytes, int maxlen)
  7. toHex(byte[] data)
  8. toHex(byte[] data)
  9. toHex(byte[] data)