Here you can find the source of toByte(final char[] charArray)
Parameter | Description |
---|---|
charArray | - Character array in ASCII |
public static byte[] toByte(final char[] charArray)
//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; } }