Convert and Append string into existing byte array

I am working on converting and existing C# project over to Java/Android. I am looking for the Java equivalent to UTF8Encoding.GetBytes(String, Int32, Int32, Byte[], Int32). Take a look at the C# code below, how do I add the string packet into the data byte array? I have looked at the String.getBytes() method but it is not the same.

int length = packet.Length;

byte[] data = new byte[6 + length + 1];
data[0] = (byte)VAR1;
data[1] = 1;

**Encoding.UTF8.GetBytes(packet, 0, length, data, 6);**

data[6 + length] = (byte)VAR2;

data[5] = (byte)(length % 256);
length /= 256;
data[4] = (byte)(length % 256);
length /= 256;
data[3] = (byte)(length % 256);
length /= 256;
data[2] = (byte)(length % 256);
Jon Skeet
people
quotationmark

Okay, given that you mean ASCII rather than UTF-8, there are two immediate options:

Intermediate byte array

byte[] encodedText = text.getBytes(StandardCharsets.US_ASCII);
System.arraycopy(encodedText, 0, data, 6, encodedText.length);

This is inefficient, but simple.

Charset directly

CharsetEncoder encoder = StandardCharsets.US_ASCII.newEncoder();
CharBuffer charBuffer = CharBuffer.wrap(text);
ByteBuffer byteBuffer = ByteBuffer.wrap(data, 6, data.length - 6);
encoder.encode(charBuffer, byteBuffer, true);

This is possibly more efficient, but more complicated to understand.

people

See more on this question at Stackoverflow