Java Char Array to Byte Array charArrayToByteArray(char[] c)

Here you can find the source of charArrayToByteArray(char[] c)

Description

char Array To Byte Array

License

Open Source License

Declaration

static byte[] charArrayToByteArray(char[] c) 

Method Source Code

//package com.java2s;
/*/*from   w  w w.java 2 s .c o m*/
 * @(#)NodeUtil.java 1.2 05/06/27
 *
 * Copyright (c) 2005 Sun Microsystems, Inc. All Rights Reserved.
 *
 * See the file "LICENSE.txt" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

public class Main {
    static byte[] charArrayToByteArray(char[] c) {
        int i = 1;
        int j = 0;
        int len = c.length;
        if (c[0] == '\0') { // even length
            byte[] bytes = new byte[(len - 1) * 2];
            for (; i < len; i++) {
                char ch = c[i];
                bytes[j++] = (byte) ((ch >> 8) & 255);
                bytes[j++] = (byte) (ch & 255);
            }
            return bytes;
        } else { // odd length
            byte[] bytes = new byte[(len - 1) * 2 - 1];
            for (; i < len - 1; i++) {
                char ch = c[i];
                bytes[j++] = (byte) ((ch >> 8) & 255);
                bytes[j++] = (byte) (ch & 255);
            }
            bytes[j++] = (byte) ((c[i] >> 8) % 255);
            return bytes;
        }
    }
}

Related

  1. char2byte(char[] chars, int offset, int len, byte[] result, int roffset)
  2. charArrayToByteArray(char charBuf[])
  3. charArrayToByteArray(char[] value)
  4. charArrayToByteArray(final char[] message)
  5. charArrayToBytes(char[] chars)
  6. chars2Bytes(char[] chars)