Java Hex Calculate toHexString(byte[] bytes)

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

Description

Convert bytes into hexidecimal string

License

Open Source License

Return

bytes as hexidecimal string, e.g. 00 FA 12 ...

Declaration

public static final String toHexString(byte[] bytes) 

Method Source Code

//package com.java2s;
/*//from   w  w  w .j  a v a2s  .co  m
 * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

public class Main {
    /** Convert bytes into hexidecimal string
     *
     * @return bytes as hexidecimal string, e.g. 00 FA 12 ...
     */
    public static final String toHexString(byte[] bytes) {
        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            short b = byteToShort(bytes[i]);
            String hex = Integer.toString(b, 0x10);

            if (b < 0x10) // just one digit, prepend '0'
                buf.append('0');

            buf.append(hex);

            if (i < bytes.length - 1)
                buf.append(' ');
        }

        return buf.toString();
    }

    /**
     * Convert (signed) byte to (unsigned) short value, i.e., all negative
     * values become positive.
     */
    private static final short byteToShort(byte b) {
        return (b < 0) ? (short) (256 + b) : (short) b;
    }
}

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, boolean addPrefix)