Java Utililty Methods Char Array to Byte Array

List of utility methods to do Char Array to Byte Array

Description

The list of methods to do Char Array to Byte Array are organized into topic(s).

Method

voidchar2byte(char[] chars, int offset, int len, byte[] result, int roffset)
charbyte
for (int i = 0; i < len; i++)
    result[roffset + i] = (byte) chars[offset + i];
byte[]charArrayToByteArray(char charBuf[])
Converts a character array (double byte chars) to a byte array.
if (charBuf == null)
    return null;
int iLen = charBuf.length;
byte buf[] = new byte[iLen];
for (int p = 0; p < iLen; p++)
    buf[p] = (byte) (charBuf[p]);
return buf;
byte[]charArrayToByteArray(char[] c)
char Array To Byte Array
int i = 1;
int j = 0;
int len = c.length;
if (c[0] == '\0') { 
    byte[] bytes = new byte[(len - 1) * 2];
    for (; i < len; i++) {
        char ch = c[i];
        bytes[j++] = (byte) ((ch >> 8) & 255);
...
byte[]charArrayToByteArray(char[] value)
convert char array value to byte array value
byte[] result = new byte[value.length];
for (int i = 0; i < value.length; i++)
    result[i] = (byte) value[i];
return result;
byte[]charArrayToByteArray(final char[] message)
Char array to byte array.
final byte[] payload = new byte[message.length];
for (int i = 0; i < message.length; i++) {
    payload[i] = (byte) (message[i] & 0xFF);
return payload;
byte[]charArrayToBytes(char[] chars)
char Array To Bytes
return charArrayToBytes(chars, chars.length);
byte[]chars2Bytes(char[] chars)
chars Bytes
byte[] bytes = new byte[chars.length * 2];
for (int i = 0; i < chars.length; i++) {
    bytes[i * 2] = (byte) ((int) chars[i] / 256);
    bytes[i * 2 + 1] = (byte) (chars[i] % 256);
return bytes;
byte[]chars2Bytes(char[] chars)
chars Bytes
if (null == chars) {
    return null;
Charset cs = Charset.forName("UTF-8");
CharBuffer cb = CharBuffer.allocate(chars.length);
cb.put(chars);
cb.flip();
ByteBuffer bb = cs.encode(cb);
...
byte[]charsToBytes(char[] chars)
chars To Bytes
byte[] b = new byte[chars.length << 1];
for (int i = 0; i < chars.length; i++) {
    char strChar = chars[i];
    int bpos = i << 1;
    b[bpos] = (byte) ((strChar & 0xFF00) >> 8);
    b[bpos + 1] = (byte) (strChar & 0x00FF);
return b;
...
byte[]charsToBytes(char[] chars)
Converts chars to bytes without using any external functions that might allocate additional buffers for the potentially sensitive data.
byte[] bytes = new byte[chars.length * 2];
for (int i = 0; i < chars.length; i++) {
    char v = chars[i];
    bytes[i * 2] = (byte) (0xff & (v >> 8));
    bytes[i * 2 + 1] = (byte) (0xff & (v));
return bytes;