Convert a byte array to a concise, readable string suitable for use in toString methods of the *Stat classes. - Java Collection Framework

Java examples for Collection Framework:Array Convert

Description

Convert a byte array to a concise, readable string suitable for use in toString methods of the *Stat classes.

Demo Code

/*-//  ww  w  .  j  a  v a2s . c om
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2001,2007 Oracle.  All rights reserved.
 *
 * $Id: DbUtil.java,v 12.5 2007/05/17 15:15:42 bostic Exp $
 */
//package com.java2s;

public class Main {
    /**
     *  Convert a byte array to a concise, readable string suitable
     *  for use in toString methods of the *Stat classes.
     *
     * @return    Description of the Return Value
     */
    public static String byteArrayToString(byte[] barr) {
        if (barr == null) {
            return "null";
        }

        StringBuffer sb = new StringBuffer();
        int len = barr.length;
        for (int i = 0; i < len; i++) {
            sb.append('x');
            int val = (barr[i] >> 4) & 0xf;
            if (val < 10) {
                sb.append((char) ('0' + val));
            } else {
                sb.append((char) ('a' + val - 10));
            }
            val = barr[i] & 0xf;
            if (val < 10) {
                sb.append((char) ('0' + val));
            } else {
                sb.append((char) ('a' + val - 10));
            }
        }
        return sb.toString();
    }
}

Related Tutorials