Converts a byte-array to the corresponding hexstring - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte-array to the corresponding hexstring

Demo Code

/*******************************************************************************
 * Copyright (c) 2008 JCrypTool Team and Contributors
 * /*from   w  ww  . j  a  v  a  2 s . com*/
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] input = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHexString(input));
    }

    private static final char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * Converts a byte-array to the corresponding hexstring
     * 
     * @param input - the byte-array to be converted
     * 
     * @return the corresponding hexstring
     */
    public static String toHexString(byte[] input) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < input.length; i++) {
            result.append(HEX_CHARS[(input[i] >>> 4) & 0x0f]);
            result.append(HEX_CHARS[(input[i]) & 0x0f]);
        }
        return result.toString();
    }

    /**
     * Converts a byte-array to the corresponding hexstring
     * 
     * @param input - the byte-array to be converted
     * @param seperator - a seperator string
     * 
     * @return the corresponding hexstring
     */
    public static String toHexString(byte[] input, String seperator) {
        StringBuffer result = new StringBuffer();

        for (int i = 0; i < input.length; i++) {
            result.append(HEX_CHARS[(input[i] >>> 4) & 0x0f]);
            result.append(HEX_CHARS[(input[i]) & 0x0f]);
            if (i < input.length - 1) {
                result.append(seperator);
            }
        }
        return result.toString();
    }
}

Related Tutorials