Convert char array to Byte Array - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Convert char array to Byte Array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        char[] chars = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.', 'c',
                'o', 'm', 'a', '1', };
        System.out.println(java.util.Arrays.toString(toByteArray(chars)));
    }/*from w  w  w  .j a v  a  2s  . c o m*/

    public static byte[] toByteArray(char[] chars) {
        byte[] bytes = new byte[chars.length];

        for (int i = 0; i != bytes.length; i++) {
            bytes[i] = (byte) chars[i];
        }

        return bytes;
    }

    public static byte[] toByteArray(String string) {
        byte[] bytes = new byte[string.length()];

        for (int i = 0; i != bytes.length; i++) {
            char ch = string.charAt(i);

            bytes[i] = (byte) ch;
        }

        return bytes;
    }
}

Related Tutorials