Interpret the byte array as chars as far as possible. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Interpret the byte array as chars as far as possible.

Demo Code

/*//from  w w  w  .  j  a  va2s  . c  o  m
 * silvertunnel.org Netlib - Java library to easily access anonymity networks
 * Copyright (c) 2009-2012 silvertunnel.org
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;

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

    private static final char SPECIAL_CHAR = '?';

    /**
     * Interpret the byte array as chars as far as possible.
     * 
     * @param b
     * @return
     */
    public static String showAsStringDetails(byte[] b) {
        StringBuffer result = new StringBuffer(b.length);
        for (int i = 0; i < b.length; i++) {
            result.append(asCharDetail(b[i]));
        }
        return result.toString();
    }

    /**
     * See also: BufferedLogger.log().
     * 
     * @param b
     * @return b as printable char; or as ?XX if not printable where XX is the hex code
     */
    public static String asCharDetail(byte b) {
        if (b < ' ' || b > 127) {
            // add hex value (always two digits)
            int i = b < 0 ? 256 + b : b;
            String hex = Integer.toHexString(i);
            if (hex.length() < 2) {
                return SPECIAL_CHAR + "0" + hex;
            } else {
                return SPECIAL_CHAR + hex;
            }
        } else {
            return Character.toString((char) b);
        }
    }
}

Related Tutorials