Each byte stream contains many packets. This method reads first two bits and calculates number of packets in the byte stream and split it.
973823
private ArrayList<byte []> splitPackets(byte[] bin){

        ArrayList<byte []> packets = new ArrayList<byte []>();
        int noOfPackets = getLengthFromByteArray(getBytes(bin, 0, 2)); //in.read(bin, 0, 2);
        int j = 2;

        for(int i = 0; i < noOfPackets; i++){
            int sizeOfPacket = getLengthFromByteArray(getBytes(bin, j, j + 2));//in.read(bin, j, j+2);
            byte[] packet = Arrays.copyOfRange(bin, j + 2, j + 2 + sizeOfPacket);
            packets.add(packet);
            j = j + 2 + sizeOfPacket;
        }
        return packets;
    }
146547
def parse_packets(self, binary_packets):
        
        if not binary_packets:
            raise ValueError("Must supply at least one packet")
        parsed_packets = []

        if not self._current_tshark:
            self.eventloop.run_until_complete(self._get_tshark_process())
        for binary_packet in binary_packets:
            self._write_packet(binary_packet)

        def callback(pkt):
            parsed_packets.append(pkt)
            if len(parsed_packets) == len(binary_packets):
                raise StopCapture()

        self.eventloop.run_until_complete(self._get_parsed_packet_from_tshark(callback))
        return parsed_packets
1087503
public static byte[] readAllToBytes(final InputStream in) throws IOException {
    try {
      final ByteArrayOutputStream result = new ByteArrayOutputStream();
      final byte[] buffer = new byte[1024];
      int length;
      while ((length = in.read(buffer)) != -1) {
        result.write(buffer, 0, length);
      }
      return result.toByteArray();
    } finally {
      in.close();
    }
  }
582963
private int read(byte[] bytes, int offset, int length, Duration receiveTimeout)
            throws InterruptedException, TTransportException
    {
        long timeRemaining = receiveTimeout.roundTo(TimeUnit.NANOSECONDS);
        lock.lock();
        try {
            while (!closed) {
                int bytesAvailable = readBuffer.readableBytes();
                if (bytesAvailable > 0) {
                    int begin = readBuffer.readerIndex();
                    readBuffer.readBytes(bytes, offset, Math.min(bytesAvailable, length));
                    int end = readBuffer.readerIndex();
                    return end - begin;
                }
                if (timeRemaining <= 0) {
                    break;
                }
                timeRemaining = condition.awaitNanos(timeRemaining);
                if (exception != null) {
                    try {
                        throw new TTransportException(exception);
                    }
                    finally {
                        exception = null;
                        closed = true;
                        close();
                    }
                }
            }
            if (closed) {
                throw new TTransportException("channel closed !");
            }
        }
        finally {
            lock.unlock();
        }
        throw new TTransportException(String.format("receive timeout, %d ms has elapsed", receiveTimeout.toMillis()));
    }
1300531
def frombytes(self, bytes, offset=0):
        
        for b in bytes:
            self._buf[offset] = b
            offset += 1
637582
void getBytes(byte[] output) {
        if (m_totalAvailable < output.length) {
            throw new IllegalStateException("Requested " + output.length + " bytes; only have "
                    + m_totalAvailable + " bytes; call tryRead() first");
        }

        int bytesCopied = 0;
        while (bytesCopied < output.length) {
            BBContainer firstC = m_readBBContainers.peekFirst();
            if (firstC == null) {
                // Steal the write buffer
                m_poolBBContainer.b().flip();
                m_readBBContainers.add(m_poolBBContainer);
                firstC = m_poolBBContainer;
                m_poolBBContainer = null;
            }
            ByteBuffer first = firstC.b();
            assert first.remaining() > 0;

            // Copy bytes from first into output
            int bytesRemaining = first.remaining();
            int bytesToCopy = output.length - bytesCopied;
            if (bytesToCopy > bytesRemaining) bytesToCopy = bytesRemaining;
            first.get(output, bytesCopied, bytesToCopy);
            bytesCopied += bytesToCopy;
            m_totalAvailable -= bytesToCopy;

            if (first.remaining() == 0) {
                // read an entire block: move it to the empty buffers list
                m_readBBContainers.poll();
                firstC.discard();
            }
        }
    }
296350
@Override
  public int read(byte[] b, int off, int len) throws IOException {
    int bytes = inner.read(b, off, Math.min(len, remaining));
    if (bytes > 0) {
      remaining -= bytes;
    }
    return bytes;
  }
357096
private static final void splitSamplesToBytes(int[] samples, int totalSamples,
    int bytesPerSample, byte[] dataMD5) {
    int destIndexBase = 0;
    int i = 0;
    
    switch(bytesPerSample) {
      case 3:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 16);
        }
        break;
      case 2:
        for(; i < totalSamples; i++) {
        dataMD5[destIndexBase++] = (byte)(samples[i]);
        dataMD5[destIndexBase++] = (byte)(samples[i] >> 8);
        }
        break;
      case 1:
        for(; i < totalSamples; i++) {
        dataMD5[i] = (byte)samples[i];
        }
    }
  }
1218606
private static byte readByte(boolean[] rawbits, int startIndex) {
    int n = rawbits.length - startIndex;
    if (n >= 8) {
      return (byte) readCode(rawbits, startIndex, 8);
    }
    return (byte) (readCode(rawbits, startIndex, n) << (8 - n));
  }
811517
def read_bytes(self, count):
        """"""
        if self.pos + count > self.remaining_length:
            return NC.ERR_PROTOCOL, None
        
        ba = bytearray(count)
        for x in xrange(0, count):
            ba[x] = self.payload[self.pos]
            self.pos += 1
        
        return NC.ERR_SUCCESS, ba
149146
private static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        byte[] buf = new byte[4096];

        while (true) {
            int r = is.read(buf);
            if (r == -1) {
                out.flush();
                return out.toByteArray();
            }
            out.write(buf, 0, r);
        }
    }
471342
public byte[] getPacketBytes() {
        byte[] result = new byte[packetBytes.length];
        System.arraycopy(packetBytes, 0, result, 0, packetBytes.length);
        return result;
    }
413388
public int decode(final InputStream stream, final ByteBuffer buffer) throws IOException {
        if (reachedEOF) {
            return -1;
        }

        // TODO: Don't decode more than single runs, because some writers add pad bytes inside the stream...
        while (buffer.hasRemaining()) {
            int n;
            
            if (splitRun) {
                // Continue run
                n = leftOfRun;
                splitRun = false;
            }
            else {
                // Start new run
                int b = stream.read();
                if (b < 0) {
                    reachedEOF = true;
                    break;
                }
                n = (byte) b;
            }

            // Split run at or before max
            if (n >= 0 && n + 1 > buffer.remaining()) {
                leftOfRun = n;
                splitRun = true;
                break;
            }
            else if (n < 0 && -n + 1 > buffer.remaining()) {
                leftOfRun = n;
                splitRun = true;
                break;
            }

            try {
                if (n >= 0) {
                    // Copy next n + 1 bytes literally
                    readFully(stream, buffer, sample.length * (n + 1));
                }
                // Allow -128 for compatibility, see above
                else if (disableNoOp || n != -128) {
                    // Replicate the next byte -n + 1 times
                    for (int s = 0; s < sample.length; s++) {
                        sample[s] = readByte(stream);
                    }

                    for (int i = -n + 1; i > 0; i--) {
                        buffer.put(sample);
                    }
                }
                // else NOOP (-128)
            }
            catch (IndexOutOfBoundsException e) {
                throw new DecodeException("Error in PackBits decompression, data seems corrupt", e);
            }
        }

        return buffer.position();
    }
438667
int read(byte[] buffer, int length, int bigendianp, int word, int sgned,
            int[] bitstream) {
        int host_endian = host_is_big_endian();
        int index = 0;

        while (true) {
            if (decode_ready) {
                float[][] pcm;
                float[][][] _pcm = new float[1][][];
                int[] _index = new int[getInfo(-1).channels];
                int samples = vd.synthesis_pcmout(_pcm, _index);
                pcm = _pcm[0];
                if (samples != 0) {
                    // yay! proceed to pack data into the byte buffer
                    int channels = getInfo(-1).channels;
                    int bytespersample = word * channels;
                    if (samples > length / bytespersample) {
                        samples = length / bytespersample;
                    }

                    // a tight loop to pack each size
                    {
                        int val;
                        if (word == 1) {
                            int off = (sgned != 0 ? 0 : 128);
                            for (int j = 0; j < samples; j++) {
                                for (int i = 0; i < channels; i++) {
                                    val = (int) (pcm[i][_index[i] + j] * 128. + 0.5);
                                    if (val > 127) {
                                        val = 127;
                                    } else if (val < -128) {
                                        val = -128;
                                    }
                                    buffer[index++] = (byte) (val + off);
                                }
                            }
                        } else {
                            int off = (sgned != 0 ? 0 : 32768);

                            if (host_endian == bigendianp) {
                                if (sgned != 0) {
                                    for (int i = 0; i < channels; i++) { // It's faster in this order
                                        int src = _index[i];
                                        int dest = i;
                                        for (int j = 0; j < samples; j++) {
                                            val = (int) (pcm[i][src + j] * 32768. + 0.5);
                                            if (val > 32767) {
                                                val = 32767;
                                            } else if (val < -32768) {
                                                val = -32768;
                                            }
                                            buffer[dest] = (byte) (val >>> 8);
                                            buffer[dest + 1] = (byte) (val);
                                            dest += channels * 2;
                                        }
                                    }
                                } else {
                                    for (int i = 0; i < channels; i++) {
                                        float[] src = pcm[i];
                                        int dest = i;
                                        for (int j = 0; j < samples; j++) {
                                            val = (int) (src[j] * 32768. + 0.5);
                                            if (val > 32767) {
                                                val = 32767;
                                            } else if (val < -32768) {
                                                val = -32768;
                                            }
                                            buffer[dest] = (byte) ((val + off) >>> 8);
                                            buffer[dest + 1] = (byte) (val + off);
                                            dest += channels * 2;
                                        }
                                    }
                                }
                            } else if (bigendianp != 0) {
                                for (int j = 0; j < samples; j++) {
                                    for (int i = 0; i < channels; i++) {
                                        val = (int) (pcm[i][j] * 32768. + 0.5);
                                        if (val > 32767) {
                                            val = 32767;
                                        } else if (val < -32768) {
                                            val = -32768;
                                        }
                                        val += off;
                                        buffer[index++] = (byte) (val >>> 8);
                                        buffer[index++] = (byte) val;
                                    }
                                }
                            } else {
                                //int val;
                                for (int j = 0; j < samples; j++) {
                                    for (int i = 0; i < channels; i++) {
                                        val = (int) (pcm[i][j] * 32768. + 0.5);
                                        if (val > 32767) {
                                            val = 32767;
                                        } else if (val < -32768) {
                                            val = -32768;
                                        }
                                        val += off;
                                        buffer[index++] = (byte) val;
                                        buffer[index++] = (byte) (val >>> 8);
                                    }
                                }
                            }
                        }
                    }

                    vd.synthesis_read(samples);
                    pcm_offset += samples;
                    if (bitstream != null) {
                        bitstream[0] = current_link;
                    }
                    return (samples * bytespersample);
                }
            }

            // suck in another packet
            switch (process_packet(1)) {
                case 0:
                    return (0);
                case -1:
                    return -1;
                default:
                    break;
            }
        }
    }
499283
def read_bits(self, stream, num_bits, padded, left_right, endian):
        
        if self._cls_bits is None and padded:
            raw_bits = stream.read_bits(self.cls.width*8)
            self._cls_bits = self._endian_transform(raw_bits, endian)

        if self._cls_bits is not None:
            if num_bits > len(self._cls_bits):
                raise errors.PfpError("BitfieldRW reached invalid state")

            if left_right:
                res = self._cls_bits[:num_bits]
                self._cls_bits = self._cls_bits[num_bits:]
            else:
                res = self._cls_bits[-num_bits:]
                self._cls_bits = self._cls_bits[:-num_bits]

            return res

        else:
            return stream.read_bits(num_bits)
656096
private void readPCM() throws IOException {
        boolean wrote = false;

        while (true) { // we repeat if the bitstream is chained
            if (endOfBitStream) {
                if (!getPageAndPacket()) {
                    break;
                }
                endOfBitStream = false;
            }

            if (!inited) {
                inited = true;
                return;
            }

            float[][][] _pcm = new float[1][][];
            int[] _index = new int[oggInfo.channels];
            // The rest is just a straight decode loop until end of stream
            while (!endOfBitStream) {
                while (!endOfBitStream) {
                    int result = syncState.pageout(page);

                    if (result == 0) {
                        break; // need more data
                    }

                    if (result == -1) { // missing or corrupt data at this page position
                        logger.log(Level.WARNING, "Corrupt or missing data in bitstream; continuing...");
                    } else {
                        streamState.pagein(page); // can safely ignore errors at
                        // this point
                        while (true) {
                            result = streamState.packetout(packet);

                            if (result == 0) {
                                break; // need more data
                            }
                            if (result == -1) { // missing or corrupt data at this page position
                                // no reason to complain; already complained above
                            } else {
                                // we have a packet.  Decode it
                                int samples;
                                if (vorbisBlock.synthesis(packet) == 0) { // test for success!
                                    dspState.synthesis_blockin(vorbisBlock);
                                }

								// **pcm is a multichannel float vector.  In stereo, for
                                // example, pcm[0] is left, and pcm[1] is right.  samples is
                                // the size of each channel.  Convert the float values
                                // (-1.<=range<=1.) to whatever PCM format and write it out
                                while ((samples = dspState.synthesis_pcmout(_pcm,
                                        _index)) > 0) {
                                    float[][] pcm = _pcm[0];
                                    //boolean clipflag = false;
                                    int bout = (samples < convsize ? samples
                                            : convsize);

									// convert floats to 16 bit signed ints (host order) and
                                    // interleave
                                    for (int i = 0; i < oggInfo.channels; i++) {
                                        int ptr = i * 2;
                                        //int ptr=i;
                                        int mono = _index[i];
                                        for (int j = 0; j < bout; j++) {
                                            int val = (int) (pcm[i][mono + j] * 32767.);
                                            // might as well guard against clipping
                                            if (val > 32767) {
                                                val = 32767;
                                            }
                                            if (val < -32768) {
                                                val = -32768;
                                            }
                                            if (val < 0) {
                                                val = val | 0x8000;
                                            }

                                            if (bigEndian) {
                                                convbuffer[ptr] = (byte) (val >>> 8);
                                                convbuffer[ptr + 1] = (byte) (val);
                                            } else {
                                                convbuffer[ptr] = (byte) (val);
                                                convbuffer[ptr + 1] = (byte) (val >>> 8);
                                            }
                                            ptr += 2 * (oggInfo.channels);
                                        }
                                    }

                                    int bytesToWrite = 2 * oggInfo.channels * bout;
                                    if (bytesToWrite >= pcmBuffer.remaining()) {
                                        logger.log(Level.WARNING, "Read block from OGG that was too big to be buffered: {0}", bytesToWrite);
                                    } else {
                                        pcmBuffer.put(convbuffer, 0, bytesToWrite);
                                    }

                                    wrote = true;
                                    dspState.synthesis_read(bout); // tell libvorbis how
                                    // many samples we
                                    // actually consumed
                                }
                            }
                        }
                        if (page.eos() != 0) {
                            endOfBitStream = true;
                        }

                        if ((!endOfBitStream) && (wrote)) {
                            return;
                        }
                    }
                }

                if (!endOfBitStream) {
                    bytes = 0;
                    int index = syncState.buffer(4096);
                    if (index >= 0) {
                        buffer = syncState.data;
                        try {
                            bytes = input.read(buffer, index, 4096);
                        } catch (Exception e) {
                            logger.log(Level.WARNING, "Failure during vorbis decoding", e);
                            endOfStream = true;
                            return;
                        }
                    } else {
                        bytes = 0;
                    }
                    syncState.wrote(bytes);
                    if (bytes == 0) {
                        endOfBitStream = true;
                    }
                }
            }

			// clean up this logical bitstream; before exit we see if we're
            // followed by another [chained]
            streamState.clear();

			// ogg_page and ogg_packet structs always point to storage in
            // libvorbis.  They're never freed or manipulated directly
            vorbisBlock.clear();
            dspState.clear();
            oggInfo.clear(); // must be called last
        }

        // OK, clean up the framer
        syncState.clear();
        endOfStream = true;
    }
345007
public void readFrom(InputStream is) throws IOException {
        while(true) {
            if(count==buf.length) {
                // reallocate
                byte[] data = new byte[buf.length*2];
                System.arraycopy(buf,0,data,0,buf.length);
                buf = data;
            }

            int sz = is.read(buf,count,buf.length-count);
            if(sz<0)     return;
            count += sz;
        }
    }