2
\$\begingroup\$

I need to create a byte array with 100 bytes from a string. The length of the string is unknown but it is always less than 100 bytes. So if the string is 65 bytes then i need the array to be 35 zero bytes and then the String bytes to follow.

At the moment i have something like this, that does the job, but maybe something prettier and optimized is possible :)

    String string = "asdf";
    byte[] stringBytes = string.getBytes();
    ByteArrayOutputStream outputStream = outputStream = new ByteArrayOutputStream();
    outputStream.write(new byte[100 - stringBytes.length]);
    outputStream.write(stringBytes);    
    byte[] result = outputStream.toByteArray();
\$\endgroup\$
2
  • \$\begingroup\$ There's no need for the OutputStream. Just do new byte[100] and use System.arraycopy to transfer the bytes into it. \$\endgroup\$ Commented Nov 12, 2015 at 13:10
  • \$\begingroup\$ Yes, I would imagine something prettier and optimized is possible \$\endgroup\$
    – Dave
    Commented Nov 12, 2015 at 13:20

1 Answer 1

3
\$\begingroup\$

You can try

String string = "asdf";
byte[] result = new byte[100];
System.arraycopy(string.getBytes(), 0, result, 100 - string.length(), string.length());
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.