Java Convert via ByteBuffer toByte(final char[] charArray)

Here you can find the source of toByte(final char[] charArray)

Description

Converts a character array to a byte array

License

LGPL

Parameter

Parameter Description
charArray - Character array in ASCII

Return

Byte array representing chars

Declaration

public static byte[] toByte(final char[] charArray) 

Method Source Code

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

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import java.util.Arrays;

public class Main {
    /**//www.  java2  s  .  c  o m
     * Converts a character array to a byte array
     *
     * @param charArray
     *            - Character array in ASCII
     * @return Byte array representing chars
     */
    public static byte[] toByte(final char[] charArray) {
        final byte[] byteArray = new byte[charArray.length << 1];

        int bpos = 0;
        for (final char element : charArray) {
            if ((byte) ((element & 0xFF00) >> 8) != 0) {
                byteArray[bpos] = (byte) ((element & 0xFF00) >> 8);
                bpos++;
            }

            byteArray[bpos] = (byte) (element & 0x00FF);
            bpos++;
        }

        return Arrays.copyOf(byteArray, bpos);
    }

    /**
     * Converts a character array to a byte array
     *
     * @param charArray
     *            - Character array
     * @param enc
     *            - Codification of the characters
     * @return Byte array representing characters, password safe
     * @throws CharacterCodingException
     *             Error when coding
     */
    public static byte[] toByte(final char[] charArray, final String enc) throws CharacterCodingException {
        final Charset charset = Charset.forName(enc);
        final CharsetEncoder encoder = charset.newEncoder();

        final CharBuffer charB = CharBuffer.wrap(charArray);
        final ByteBuffer byteB = encoder.encode(charB);

        final byte[] ba1 = new byte[byteB.limit()];
        byteB.get(ba1);

        return ba1;
    }
}

Related

  1. toBuffer(byte[] arr)
  2. toBuffer(int[] array)
  3. toBuffer(Serializable obj)
  4. toBuffer(String spacedHex)
  5. toByte(char data)
  6. toByte(int input, int count)
  7. toByteArray(BitSet bits)
  8. toByteArray(char[] chars)
  9. toByteArray(double value)