Here you can find the source of stringToByteArray(String str, Charset charsetForEncoding, int lenOfByteArray, byte filler)
Parameter | Description |
---|---|
str | String to encode. |
charsetForEncoding | Charset used for encoding. |
lenOfByteArray | length of the resulting byte array. |
filler | byte used for pedding if encoded string is shorter than given length. |
public static byte[] stringToByteArray(String str, Charset charsetForEncoding, int lenOfByteArray, byte filler)
//package com.java2s; /*/*w w w. j av a 2 s .c om*/ Copyright 2015 Rudolf Fiala This file is part of Alpheus AFP Parser. Alpheus AFP Parser is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Alpheus AFP Parser is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Alpheus AFP Parser. If not, see <http://www.gnu.org/licenses/> */ import java.nio.charset.Charset; public class Main { /** * Converts the given {@link String} into a byte array of given length using the given {@link * Charset} for encoding. If the encoded bytes of the given {@link String} is shorter than the * given length, the additional encoded bytes are filled with given byte filler. If the encoded * bytes of the given {@link String} is longer than the given length, the additional encoded bytes * are truncated. * * @param str {@link String} to encode. * @param charsetForEncoding {@link Charset} used for encoding. * @param lenOfByteArray length of the resulting byte array. * @param filler byte used for pedding if encoded string is shorter than given * length. * @return byte array containing the resulting encoded {@link String} */ public static byte[] stringToByteArray(String str, Charset charsetForEncoding, int lenOfByteArray, byte filler) { if (charsetForEncoding == null) charsetForEncoding = Charset.defaultCharset(); byte[] encoded = str != null && str.length() > 0 ? str.getBytes(charsetForEncoding) : new byte[] {}; byte[] result = new byte[lenOfByteArray]; for (int i = 0; i < lenOfByteArray; i++) { if (i < encoded.length) { result[i] = encoded[i]; } else { result[i] = filler; } } return result; } }