How can I convert a string or multiple strings to different ranges in a byte array in Java?

I have a bunch of strings for fields like name, user id, email, etc. that need to go into a byte [] array of a certain size (1024 bytes).

I'd love to find a method / function that would allow me to simply use my bufferPosition index variable like this:

byteArray [bufferPosition] + = name + = userID + = email;

bufferPosition + = name.length () + = userID.length () + = email.length ();

So far, all I have found are ways to directly convert strings to byte arrays and some seemingly tedious ways to solve this problem (e.g. treating each element of the string as a character, converting to byte, creating a loop and inserting each element) ...

EDIT: Follow-up

I also have fields that are String [] arrays of 14 elements. This would be the most tedious part. Will I be able to use a similar one for each loop? I guess there is a very clever way to figure this out.

+3


source to share


2 answers


Try this using System.arraycopy :

// some dummy data
byte[] myByteArr = new byte[1024];
String name = "name";
String userId = "userId";
int bufferPosition = 0;

// repeat this for all of your fields...
byte[] stringBytes = name.getBytes();  // get bytes from string
System.arraycopy(stringBytes, 0, myByteArr, bufferPosition, stringBytes.length);  // copy src to dest
bufferPosition += stringBytes.length;  // advance index

      

You can do it using a loop this way (using your field names):



String[] myFields = new String[]{name, userID, email};  // put your fields in an array or list

// loop through each field and copy the data
for (String field : myFields) {
    byte[] stringBytes = field.getBytes();  // get bytes from string
    System.arraycopy(stringBytes, 0, myByteArr, bufferPosition, stringBytes.length);  // copy src to dest
    bufferPosition += stringBytes.length;  // advance index
}

      

You will need to make sure you don't exceed the bounds of the array, but this is a simple example.

+3


source


Slightly improved version (thanks to @Ryan J):

private static byte[] bytesFromStrings(final String... data) throws UnsupportedEncodingException {
    final byte[] result = new byte[1024];
    int bufferPosition = 0;
    if (data != null) {
        for (String d : data) {
            final byte[] stringBytes = d.getBytes("UTF-8");
            if (bufferPosition > 1023) {
                break;
            } else {
                System.arraycopy(stringBytes, 0, result, bufferPosition, Integer.min(1024 - bufferPosition, stringBytes.length));
                bufferPosition = Integer.min(bufferPosition + stringBytes.length, 1024);
            }   
        }
    }
    return result;
}

      



.. with null / overflow handling and dynamic data :-)

EDIT: ... and some portability considerations. ( d.getBytes()

)

+1


source







All Articles