0

I'm trying to remove a written string from a byte array and maintain the original separate objects:

byte[] data... // this is populated with the following:
// 00094E6966747943686174001C00074D657373616765000B4372616674656446757279000474657374
// to string using converter : "    ChannelMessageUsernametest"
// notice that tab/whitespace, ignore quotes
// The byte array was compiled by writing the following (writeUTF from a writer):
// Channel
// Message
// Username
// test

Now I'm trying to strip Channel from the byte array:

ByteArrayDataInput input = ByteStreams.newDataInput(message);
String channel = input.readUTF(); // Channel, don't want this
String message = input.readUTF(); // Message
// works good, but I don't want Channel,
// and I can't remove it from the data before it arrives,
// I have to work with what I have

Here is my problem:

byte[] newData = Arrays.copyOfRange(data, channel.length() + 2, data.length)
// I use Arrays.copyOfRange to strip the whitespace (I assume it's not needed)
// As well, since it's inclusive of length size, I have to add 1 more,
// resulting in channel.length() + 1
// ...
ByteArrayDataInput newInput = ByteStreams.newDataInput(message);
String channel = newInput.readUTF(); // MessageUsernametext

See how I lose the separation of the objects, how can I keep the original "sections" of objects in the original byte[] data inside byte[] newData.

  • It's safe to assume that String channel (before and after stripping) is a string
  • It's NOT safe to assume that every object is a string, assume everything is random, because it is

2 Answers 2

1

As long as you can guarantee that channel is always in a reasonable character range (for example alphanumeric), changing the channel.length() + 2 to channel.length() + 4 should be sufficient.

Sign up to request clarification or add additional context in comments.

Comments

0

Java Strings have 16-bit elements, so it is safe to convert a byte array into a String, although not as memory efficient:

private byte[] removeElements(byte[] data, int fromIndex, int len) {
       String str1 = new String(data).substring(0,fromIndex);
       String str2 = new String(data).substring(fromIndex+len,data.length);
       return (str1+str2).getBytes();
}

In the same manner, you can also search for a String inside the byte array:

private int findStringInByteArray(byte[] mainByte, String str, int fromIndex) {
    String main = new String(mainByte);
    return main.indexOf(str,fromIndex);
}

Now you can call these methods together:

byte[] newData = removeElements(
    data,
    findStringInByteArray(data,channel,0),
    channel.length() );

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.