Java Byte Array Create toByteArray(final char[] array)

Here you can find the source of toByteArray(final char[] array)

Description

Converts array of char to byte array.

License

Apache License

Parameter

Parameter Description
array the array

Return

the byte[]

Declaration

public static byte[] toByteArray(final char[] array) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*  ww w .  jav  a  2s  . c  o m*/
     * Converts array of char to byte array.
     *
     * @param array the array
     * @return the byte[]
     */
    public static byte[] toByteArray(final char[] array) {
        final byte[] result = new byte[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            result[2 * i] = (byte) ((array[i] & 0xFF00) >> 8);
            result[2 * i + 1] = (byte) (array[i] & 0x00FF);
        }
        return result;
    }

    /**
     * Creates byte array with bit representation of int.
     *
     * @param size the size
     * @return the byte[4]
     */
    public static byte[] toByteArray(final int size) {
        final byte[] result = new byte[4];
        for (int i = 0; i < 4; i++)
            result[i] = (byte) (size >> 24 - i * 8);
        return result;
    }

    /**
     * Creates byte array with bit representation of long.
     *
     * @param size the size
     * @return the byte[8]
     */
    public static byte[] toByteArray(final long size) {
        final byte[] result = new byte[8];
        for (int i = 0; i < 8; i++)
            result[i] = (byte) (size >> 56 - i * 8);
        return result;
    }

    /**
     * Converts array of char to byte array.
     *
     * @param array the array
     * @return the byte[]
     */
    public static byte[] toByteArray(final short[] array) {
        final byte[] result = new byte[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            result[2 * i] = (byte) ((array[i] & 0xFF00) >> 8);
            result[2 * i + 1] = (byte) (array[i] & 0x00FF);
        }
        return result;
    }
}

Related

  1. toByteArray(char[] src)
  2. toByteArray(CharSequence hexString)
  3. toByteArray(double[][] array)
  4. toByteArray(final byte[] bytes)
  5. toByteArray(final byte[][] array)
  6. toByteArray(final char[] array)
  7. toByteArray(final int i)
  8. toByteArray(final int i)
  9. toByteArray(final int i, final byte[] output, final int offset)