2

I have a byte buffer from which i need to remove some bytes of carriage return /r and return the same byte buffer after removal. With help i was able to remove the the /r using stream as below but that return a int[], is there any way where i do not need to create another byte buffer and use the same one after removing the /r? Below is the code i used

IntStream.range(bb.position(), bb.limit())
          .filter(i -> bb.get(i) != 13)
          .map(i -> bb.get(i)) 
          .toArray();

Let me know any other way to do this?

5
  • What type of buffer do you mean, could you provide the decleration of your buffer, the ´bb´? Commented Jun 25, 2020 at 6:32
  • ByteBuffer bb = ByteBuffer.allocate(32548); Commented Jun 25, 2020 at 6:33
  • 1
    "is there any way where i do not need to create another byte buffer and use the same one after removing the /r?" – I don't understand. My answer to your previous question tells you exactly how to do this (similar to Lino's answer here), but in the comments you said you want a new buffer instance. Commented Jun 25, 2020 at 6:44
  • @Slaw as you've provided the solution in your answer to the other question, I think we can close this as a dupe? Commented Jun 25, 2020 at 6:52
  • 1
    @Lino Not sure. My answer may solve this question but the two questions themselves are different (the solution to this question in my answer was more of a "bonus"). Commented Jun 25, 2020 at 6:59

1 Answer 1

1

You could use this helper method:

public static int removeAll(ByteBuffer buf, int b) {
    int removed = 0;
    for (int i = 0, start = 0, cap = buf.capacity(); i < cap; i++) {
        byte read = buf.get(i);
        buf.put(i, (byte) 0);
        if (read != b) {
            buf.put(start++, read);
        } else {
            removed++;
        }
    }
    return removed;
}

Which you can then call like this:

removeAll(buf, '\r');

It simply iterates the buffer, and removes the bytes that are equal to the provided argument, leaving 0 at the end of the buffer to account for the missing elements.

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

2 Comments

removeAll(ByteBuffer.wrap(new byte[] {1, 2, 3, 13, 4, 5, 13}, 13) -> {0, 0, 0, 4, 5, 0, 13}   Do you need buf.put(i, (byte) 0);?
@saka1029 good catch, fixed it, by always putting a 0 at index i into the buffer, and yes it is needed, else we would have trailing bytes at the end which we have moved earlier to another position

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.