Converts a String to a byte array using ASCII translation. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a String to a byte array using ASCII translation.

Demo Code


//package com.java2s;
import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "java2s.com";
        System.out.println(java.util.Arrays.toString(fromString(s)));
    }//  w w w  . j  a v a 2 s  . c o  m

    /**
     * Converts a String to a byte array using ASCII translation. This
     * method allocates a single byte per character so it is NOT
     * possible to encode Unicode or non-ASCII characters!
     */
    public static byte[] fromString(String s) {
        if (null == s) {
            return new byte[0];
        }
        try {
            return s.getBytes("US-ASCII");
        } catch (UnsupportedEncodingException ioe) {
            return s.getBytes();
        }
    }

    /**
     * Print a byte array as a String
     */
    public static String toString(byte[] bytes) {

        StringBuilder sb = new StringBuilder(4 * bytes.length);
        sb.append("[");

        for (int i = 0; i < bytes.length; i++) {
            sb.append(unsignedByteToInt(bytes[i]));
            if (i + 1 < bytes.length) {
                sb.append(",");
            }
        }

        sb.append("]");
        return sb.toString();
    }

    /**
     * Convert an unsigned byte to an int
     */
    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }
}

Related Tutorials