Java Object Type Case cast(byte[] bytes)

Here you can find the source of cast(byte[] bytes)

Description

Byte-to-byte copy of an array of bytes to an array of chars without conversion.

License

Open Source License

Parameter

Parameter Description
bytes The bytes to cast.

Return

The same input, but as chars.

Declaration

public static char[] cast(byte[] bytes) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*w ww  .  j  a v  a2  s . com*/
     * Byte-to-byte copy of an array of chars to an array of bytes without
     * conversion (a char contains 2 bytes).
     * 
     * This method converts non-ASCII chars.
     * 
     * @param chars
     *            The chars to cast.
     * 
     * @return The same input, but as bytes.
     */
    public static byte[] cast(char[] chars) {
        byte[] bytes = new byte[chars.length << 1];
        for (int i = 0; i < chars.length; i++) {
            int pos = i << 1;
            bytes[pos] = (byte) ((chars[i] & 0xFF00) >> 8);
            bytes[pos + 1] = (byte) (chars[i] & 0x00FF);
        }
        return bytes;
    }

    /**
     * Byte-to-byte copy of an array of bytes to an array of chars without
     * conversion. (a char contains 2 bytes).
     * 
     * This method converts from non-ASCII chars.
     * 
     * @param bytes
     *            The bytes to cast.
     * 
     * @return The same input, but as chars.
     */
    public static char[] cast(byte[] bytes) {
        char[] chars = new char[bytes.length >> 1];
        for (int i = 0; i < chars.length; i++) {
            int pos = i << 1;
            char c = (char) (((bytes[pos] & 0x00FF) << 8) + (bytes[pos + 1] & 0x00FF));
            chars[i] = c;
        }
        return chars;
    }
}

Related

  1. cast(B b0, Class cls)
  2. cast(byte b)
  3. cast(Class c)
  4. cast(Class c, Object o)
  5. cast(Class clazz, Object o, T def)
  6. cast(Class clazz, Object obj)