Java String to Array stringToByteArray(String text, int length)

Here you can find the source of stringToByteArray(String text, int length)

Description

Parse a human readable string into a byte array, truncating or padding with zeros (if necessary) so the array has the specified length.

License

Open Source License

Parameter

Parameter Description
text The string to be parsed
length Length of the returned array.

Return

A byte array of specified length, with each of the first length characters converted to a byte. If length is longer than the provided string length, will be filled with zeroes.

Declaration

public static byte[] stringToByteArray(String text, int length) 

Method Source Code

//package com.java2s;
/**//from  ww  w  .ja v a 2s  . c om
 * Oshi (https://github.com/dblock/oshi)
 *
 * Copyright (c) 2010 - 2016 The Oshi Project Team
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Maintainers:
 * dblock[at]dblock[dot]org
 * widdis[at]gmail[dot]com
 * enrico.bianchi[at]gmail[dot]com
 *
 * Contributors:
 * https://github.com/dblock/oshi/graphs/contributors
 */

import java.util.Arrays;

public class Main {
    /**
     * Parse a human readable string into a byte array, truncating or padding
     * with zeros (if necessary) so the array has the specified length.
     *
     * @param text
     *            The string to be parsed
     * @param length
     *            Length of the returned array.
     * @return A byte array of specified length, with each of the first length
     *         characters converted to a byte. If length is longer than the
     *         provided string length, will be filled with zeroes.
     */
    public static byte[] stringToByteArray(String text, int length) {
        return Arrays.copyOf(text.getBytes(), length);
    }
}

Related

  1. stringToArray(final String data, final String delim)
  2. stringToArray(String charc, String commas)
  3. stringToArray(String inputVal, String delimiter)
  4. stringToArray(String s)
  5. stringToArray(String str, String separator)