Java Byte Array Create toBytes(String s, int len, byte pad)

Here you can find the source of toBytes(String s, int len, byte pad)

Description

Routine to convert a string to bytes and pad with a character up to a given length.

License

Open Source License

Parameter

Parameter Description
s The original string.
len The length to pad to.
pad The byte used to pad.

Return

An array created from the string.

Declaration

public static byte[] toBytes(String s, int len, byte pad) 

Method Source Code

//package com.java2s;
/*//from w w  w .j  a va2  s .com
 * Copyright (C) 2006 Steve Ratcliffe
 * 
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 * 
 *  This program 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.
 * 
 * 
 * Author: Steve Ratcliffe
 * Create date: 03-Dec-2006
 */

public class Main {
    /**
     * Routine to convert a string to bytes and pad with a character up
     * to a given length.
     * Only to be used for strings that are expressible in latin1.
     *
     * @param s The original string.
     * @param len The length to pad to.
     * @param pad The byte used to pad.
     * @return An array created from the string.
     */
    public static byte[] toBytes(String s, int len, byte pad) {
        if (s == null)
            throw new IllegalArgumentException("null string provided");

        byte[] out = new byte[len];
        for (int i = 0; i < len; i++) {
            if (i > s.length()) {
                out[i] = pad;
            } else {
                out[i] = (byte) s.charAt(i);
            }
        }
        return out;
    }

    public static byte[] toBytes(String s) {
        return toBytes(s, s.length(), (byte) 0);
    }
}

Related

  1. toBytes(String hexStr)
  2. toBytes(String hexString)
  3. toBytes(String hexString)
  4. toBytes(String name)
  5. toBytes(String s)
  6. toBytes(String str, byte[] bytes, int index)
  7. toBytes4(int n)
  8. toBytes4HexString(String str, char... separateds)
  9. toBytesBE(long v)