Java Hex Calculate toHexString(byte[] buf)

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

Description

Convenience call for #toHexString(byte[],String,int) , where sep = null; lineLen = Integer.MAX_VALUE.

License

Apache License

Parameter

Parameter Description
buf a parameter

Declaration

public static String toHexString(byte[] buf) 

Method Source Code

//package com.java2s;
/*// w  w w. ja v  a 2s  .c om
 * Copyright 2009-2013 Scale Unlimited
 *
 * 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 char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Convenience call for {@link #toHexString(byte[], String, int)}, where
     * <code>sep = null; lineLen = Integer.MAX_VALUE</code>.
     * 
     * @param buf
     */
    public static String toHexString(byte[] buf) {
        return toHexString(buf, null, Integer.MAX_VALUE);
    }

    /**
     * Get a text representation of a byte[] as hexadecimal String, where each
     * pair of hexadecimal digits corresponds to consecutive bytes in the array.
     * 
     * @param buf
     *            input data
     * @param sep
     *            separate every pair of hexadecimal digits with this separator,
     *            or null if no separation is needed.
     * @param lineLen
     *            break the output String into lines containing output for
     *            lineLen bytes.
     */
    public static String toHexString(byte[] buf, String sep, int lineLen) {
        if (buf == null)
            return null;
        if (lineLen <= 0)
            lineLen = Integer.MAX_VALUE;
        StringBuffer res = new StringBuffer(buf.length * 2);
        for (int i = 0; i < buf.length; i++) {
            int b = buf[i];
            res.append(HEX_DIGITS[(b >> 4) & 0xf]);
            res.append(HEX_DIGITS[b & 0xf]);
            if (i > 0 && (i % lineLen) == 0)
                res.append('\n');
            else if (sep != null && i < lineLen - 1)
                res.append(sep);
        }
        return res.toString();
    }
}

Related

  1. toHexString(byte[] ba)
  2. toHexString(byte[] ba, int offset, int length)
  3. toHexString(byte[] binary)
  4. toHexString(byte[] binaryData)
  5. toHexString(byte[] block)
  6. toHexString(byte[] buf)
  7. toHexString(byte[] buf, int offset, int len)
  8. toHexString(byte[] buffer)
  9. toHexString(byte[] byteArray)