public static byte[] toFixedLengthBytes(final String str, final int length) {
        if (length < 0) {
            throw new ArrayIndexOutOfBoundsException(length);
        }
        final byte[] b1 = toBytes(str);
        if (b1 == null) {
            return new byte[length];
        }

        if (b1.length > length) {
            throw new StringIndexOutOfBoundsException("String is longer then target length of bytes.");
        }
        byte[] b = new byte[length];
        System.arraycopy(b1, 0, b, 0, b1.length);

        return b;
    }
copy google protocol buffer
https://github.com/google/protobuf/blob/master/java/src/main/java/com/google/protobuf/CodedOutputStream.java
commons/src/main/java/com/navercorp/pinpoint/common/util/BytesUtils.java