Advertisement
djxak

ByteBuffer to send bytes in chunks of 8 (only 1 array copy operation)

Dec 8th, 2021
1,048
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. package com.example;
  2.  
  3. import java.nio.ByteBuffer;
  4. import java.util.Arrays;
  5.  
  6. public class ByteBufferTests {
  7.  
  8.     private ByteBuffer buf = ByteBuffer.allocate(8);
  9.  
  10.     public static void main(String[] args) {
  11.         ByteBufferTests bbt = new ByteBufferTests();
  12.         bbt.onReceive(new byte[]{1, 2, 3});
  13.         bbt.onReceive(new byte[]{4, 5});
  14.         bbt.onReceive(new byte[]{6, 7, 8});
  15.         bbt.onReceive(new byte[]{9, 10, 11, 12, 13, 14, 15, 16});
  16.         bbt.onReceive(new byte[]{17, 18, 19, 20, 21, 22, 23, 24, 25, 26});
  17.  
  18.         bbt.buf.flip();
  19.         byte[] bytes = new byte[bbt.buf.remaining()];
  20.         bbt.buf.get(bytes);
  21.         System.out.println("Remaining bytes: " + Arrays.toString(bytes));
  22.     }
  23.  
  24.     public void onReceive(byte[] bytes) {
  25.         ByteBuffer rBuf = ByteBuffer.wrap(bytes);
  26.  
  27.         while (true) {
  28.             int maxBytesToRead = Math.min(buf.remaining(), rBuf.remaining());
  29.             for (int i = 0; i < maxBytesToRead; i++) {
  30.                 buf.put(rBuf.get());
  31.             }
  32.             if (buf.remaining() == 0) {
  33.                 byte[] nextBytes = buf.array();
  34.                 System.out.println("onNext(" + Arrays.toString(nextBytes) + ")");
  35.                 buf = ByteBuffer.allocate(8);
  36.             } else {
  37.                 break;
  38.             }
  39.         }
  40.     }
  41.  
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement