bstream is a bit stream
332049
function RarVolumeHeader(bstream) {

    var headPos = bstream.bytePtr;
    // byte 1,2
    RarEventMgr.emitInfo("Rar Volume Header @" + bstream.bytePtr);

    this.crc = bstream.readBits(16);
    RarEventMgr.emitInfo("  crc=" + this.crc);

    // byte 3
    this.headType = bstream.readBits(8);
    RarEventMgr.emitInfo("  headType=" + this.headType);

    // Get flags
    // bytes 4,5
    this.flags = {};
    this.flags.value = bstream.peekBits(16);

    RarEventMgr.emitInfo("  flags=" + RarUtils.twoByteValueToHexString(this.flags.value));
    switch (this.headType) {
        case RarUtils.VOLUME_TYPES.MAIN_HEAD:
            this.flags.MHD_VOLUME = !!bstream.readBits(1);
            this.flags.MHD_COMMENT = !!bstream.readBits(1);
            this.flags.MHD_LOCK = !!bstream.readBits(1);
            this.flags.MHD_SOLID = !!bstream.readBits(1);
            this.flags.MHD_PACK_COMMENT = !!bstream.readBits(1);
            this.flags.MHD_NEWNUMBERING = this.flags.MHD_PACK_COMMENT;
            this.flags.MHD_AV = !!bstream.readBits(1);
            this.flags.MHD_PROTECT = !!bstream.readBits(1);
            this.flags.MHD_PASSWORD = !!bstream.readBits(1);
            this.flags.MHD_FIRSTVOLUME = !!bstream.readBits(1);
            this.flags.MHD_ENCRYPTVER = !!bstream.readBits(1);
            bstream.readBits(6); // unused
            break;
        case RarUtils.VOLUME_TYPES.FILE_HEAD:
            this.flags.LHD_SPLIT_BEFORE = !!bstream.readBits(1); // 0x0001
            this.flags.LHD_SPLIT_AFTER = !!bstream.readBits(1); // 0x0002
            this.flags.LHD_PASSWORD = !!bstream.readBits(1); // 0x0004
            this.flags.LHD_COMMENT = !!bstream.readBits(1); // 0x0008
            this.flags.LHD_SOLID = !!bstream.readBits(1); // 0x0010
            bstream.readBits(3); // unused
            this.flags.LHD_LARGE = !!bstream.readBits(1); // 0x0100
            this.flags.LHD_UNICODE = !!bstream.readBits(1); // 0x0200
            this.flags.LHD_SALT = !!bstream.readBits(1); // 0x0400
            this.flags.LHD_VERSION = !!bstream.readBits(1); // 0x0800
            this.flags.LHD_EXTTIME = !!bstream.readBits(1); // 0x1000
            this.flags.LHD_EXTFLAGS = !!bstream.readBits(1); // 0x2000
            bstream.readBits(2); // unused
            RarEventMgr.emitInfo("  LHD_SPLIT_BEFORE = " + this.flags.LHD_SPLIT_BEFORE);
            break;
        default:
            bstream.readBits(16);
    }

    // byte 6,7
    this.headSize = bstream.readBits(16);
    RarEventMgr.emitInfo("  headSize=" + this.headSize);
    switch (this.headType) {
        case RarUtils.VOLUME_TYPES.MAIN_HEAD:
            this.highPosAv = bstream.readBits(16);
            this.posAv = bstream.readBits(32);
            if (this.flags.MHD_ENCRYPTVER) {
                this.encryptVer = bstream.readBits(8);
            }
            RarEventMgr.emitInfo("Found MAIN_HEAD with highPosAv=" + this.highPosAv + ", posAv=" + this.posAv);
            break;
        case RarUtils.VOLUME_TYPES.FILE_HEAD:
            this.packSize = bstream.readBits(32);
            this.unpackedSize = bstream.readBits(32);
            this.hostOS = bstream.readBits(8);
            this.fileCRC = bstream.readBits(32);
            this.fileTime = bstream.readBits(32);
            this.unpVer = bstream.readBits(8);
            this.method = bstream.readBits(8);
            this.nameSize = bstream.readBits(16);
            this.fileAttr = bstream.readBits(32);

            if (this.flags.LHD_LARGE) {
                RarEventMgr.emitInfo("Warning: Reading in LHD_LARGE 64-bit size values");
                this.HighPackSize = bstream.readBits(32);
                this.HighUnpSize = bstream.readBits(32);
            } else {
                this.HighPackSize = 0;
                this.HighUnpSize = 0;
                if (this.unpackedSize == 0xffffffff) {
                    this.HighUnpSize = 0x7fffffff
                    this.unpackedSize = 0xffffffff;
                }
            }
            this.fullPackSize = 0;
            this.fullUnpackSize = 0;
            this.fullPackSize |= this.HighPackSize;
            this.fullPackSize <<= 32;
            this.fullPackSize |= this.packSize;

            // read in filename
            this.filename = bstream.readBytes(this.nameSize);
            var _i,
                fileNameStr = '';

            for (_i = 0; _i < this.filename.length; _i++) {
                fileNameStr += String.fromCharCode(this.filename[_i]);
            }

            fileNameStr = fileNameStr.replace(/\\/g, "/");

            this.filename = fileNameStr;

            if (this.flags.LHD_SALT) {
                RarEventMgr.emitInfo("Warning: Reading in 64-bit salt value");
                this.salt = bstream.readBits(64); // 8 bytes
            }

            if (this.flags.LHD_EXTTIME) {
                // 16-bit flags
                var extTimeFlags = bstream.readBits(16);

                // this is adapted straight out of arcread.cpp, Archive::ReadHeader()
                for (var I = 0; I < 4; ++I) {
                    var rmode = extTimeFlags >> ((3 - I) * 4);
                    if ((rmode & 8) == 0)
                        continue;
                    if (I != 0)
                        bstream.readBits(16);
                    var count = (rmode & 3);
                    for (var J = 0; J < count; ++J)
                        bstream.readBits(8);
                }
            }

            if (this.flags.LHD_COMMENT) {
                RarEventMgr.emitInfo("Found a LHD_COMMENT");
            }


            while (headPos + this.headSize > bstream.bytePtr) {
                bstream.readBits(1);
            }

            RarEventMgr.emitInfo("Found FILE_HEAD with packSize=" + this.packSize + ", unpackedSize= " + this.unpackedSize + ", hostOS=" + this.hostOS + ", unpVer=" + this.unpVer + ", method=" + this.method + ", filename=" + this.filename);

            break;
        default:
            RarEventMgr.emitInfo("Found a header of type 0x" + RarUtils.byteValueToHexString(this.headType));
            // skip the rest of the header bytes (for now)
            bstream.readBytes(this.headSize - 7);
            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)
1221289
public static Bits toBits(Consumer<BitOutputStream> fn) {
    try {
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      BitOutputStream out = new BitOutputStream(buffer);
      fn.accept(out);
      out.flush();
      return new Bits(buffer.toByteArray(), out.getTotalBitsWritten());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
1103793
@Override
	protected void writeByte(int value) throws BitStreamException {
		try {
			out.write(value);
		} catch (IOException e) {
			throw new BitStreamException(e);
		}
	}
1025890
void writeBoolean(ByteBuf out, final boolean value) {
        int bitCount = this.bitCount + 1;
        long bitBuffer = this.bitBuffer | (value ? 1L << 64 - bitCount : 0L);

        if (bitCount == 32) {
            out.writeInt((int) (bitBuffer >>> 32));
            bitBuffer = 0;
            bitCount = 0;
        }
        this.bitBuffer = bitBuffer;
        this.bitCount = bitCount;
    }
145910
private CBSChunk bufB(int bpv) {
    CBSChunk chk = new CBSChunk(_len,bpv);
    for(int i = 0; i < _len; ++i){
      if(isNA2(i)) chk.write(i,CBSChunk._NA);
      else if(_ms.get(i) == 1) chk.write(i, (byte)1);
      else assert _ms.get(i) == 0;
    }
    return chk;
  }
360012
function Stream(i) {
	this.offset = 0;
	if (i instanceof Buffer) {
		this.buffer = i;
	}
	else {
		this.buffer = new Buffer(i || 8192);
	}
}
858079
public final void bitcoinSerialize(OutputStream stream) throws IOException {
        // 1st check for cached bytes.
        if (payload != null && length != UNKNOWN_LENGTH) {
            stream.write(payload, offset, length);
            return;
        }

        bitcoinSerializeToStream(stream);
    }
608208
@Override
    public InputStream getBinaryStream(int columnIndex) throws SQLException {
        checkColumnBounds(columnIndex);
        try {
            return new ByteArrayInputStream(
                    table.getStringAsBytes(columnIndex - 1));
        } catch (Exception x) {
            throw SQLError.get(x);
        }
    }
530429
private byte[] bufB(int bpv) {
    assert bpv == 1 || bpv == 2 : "Only bit vectors with/without NA are supported";
    final int off = CBSChunk.OFF;
    int clen  = off + CBSChunk.clen(_len, bpv);
    byte bs[] = new byte[clen];
    // Save the gap = number of unfilled bits and bpv value
    bs[0] = (byte) (((_len*bpv)&7)==0 ? 0 : (8-((_len*bpv)&7)));
    bs[1] = (byte) bpv;

    // Dense bitvector
    int  boff = 0;
    byte b    = 0;
    int  idx  = CBSChunk.OFF;
    int j = 0;
    for (int i=0; i<_len; i++) {
      byte val = 0;
      if(_id == null || (j < _id.length && _id[j] == i)) {
        assert bpv == 2 || !isNA2(j);
        val = (byte)(isNA2(j)?CBSChunk._NA:_ls[j]);
        ++j;
      }
      if( bpv==1 )
        b = CBSChunk.write1b(b, val, boff);
      else
        b = CBSChunk.write2b(b, val, boff);
      boff += bpv;
      if (boff>8-bpv) { assert boff == 8; bs[idx] = b; boff = 0; b = 0; idx++; }
    }
    assert j == _sparseLen;
    assert bs[0] == (byte) (boff == 0 ? 0 : 8-boff):"b[0] = " + bs[0] + ", boff = " + boff + ", bpv = " + bpv;
    // Flush last byte
    if (boff>0) bs[idx] = b;
    return bs;
  }
910523
function(rc, outputStream) {
        while (rc.range <= Bottom_value) { /* do we need renormalization? */
            if (rc.low < (0xFF << SHIFT_BITS)) {//no carry possible, so output
                outputStream.writeByte(rc.buffer);
                for (; rc.help; rc.help--)
                    outputStream.writeByte(0xFF);
                rc.buffer = (rc.low >>> SHIFT_BITS) & 0xFF;
            } else if (rc.low & Top_value) { /* carry now, no future carry */
                outputStream.writeByte(rc.buffer+1);
                for (; rc.help; rc.help--)
                    outputStream.writeByte(0x00);
                rc.buffer = (rc.low >>> SHIFT_BITS) & 0xFF;
            } else {
                rc.help++;
                if (rc.help > MAX_INT)
                    throw new Error("Too many bytes outstanding, "+
                                    "file too large!");
            }
            rc.range = (rc.range << 8) >>> 0;/*ensure result remains positive*/
            rc.low = ((rc.low << 8) & (Top_value - 1)) >>> 0; /* unsigned */
            rc.bytecount++;
        }
    }
342253
def from_bytes(cls, bitstream):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the source and destination ports
        (packet.source_port,
         packet.destination_port) = bitstream.readlist('2*uint:16')

        # Store the length
        length = bitstream.read('uint:16')
        if length < 8:
            raise ValueError('Invalid UDP length')

        # Read the checksum
        packet.checksum = bitstream.read('uint:16')

        # And the rest is payload
        payload_bytes = length - 8
        packet.payload = bitstream.read('bytes:%d' % payload_bytes)

        # LISP-specific handling
        if packet.source_port == 4341 or packet.destination_port == 4341:
            # Payload is a LISP data packet
            from pylisp.packet.lisp.data import DataPacket
            packet.payload = DataPacket.from_bytes(packet.payload)
        elif packet.source_port == 4342 or packet.destination_port == 4342:
            # Payload is a LISP control message
            from pylisp.packet.lisp.control.base import ControlMessage
            packet.payload = ControlMessage.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
729891
def as_bin(self):
        """"""
        f = io.BytesIO()
        self.stream(f)
        return f.getvalue()
81388
def bitop_xor(self, dest, key, *keys):
        """"""
        return self.execute(b'BITOP', b'XOR', dest, key, *keys)
848232
@Override
	public int writeBit(int bit) throws BitStreamException {
		//TODO what is the correct behaviour here?
		//throw EOBSE or return reduced count
		if (position + bufferSize + 1 > size) throw new BitStreamException("array full");

		if (bufferSize == 0) {
			bufferBits = bit;
			bufferSize = 1;
		} else if (bufferSize + 1 <= 32) {
			bufferBits = (bufferBits << 1) | bit & 1;
			bufferSize ++;
		} else {
			flushBuffer();
			bufferBits = bit;
			bufferSize = 1;

		}

		return 1;
	}
308644
function bnpChangeBit(n, op)
{
  var r = Int128.ONE.shiftLeft(n);
  this.bitwiseTo(r, op, r);
  return r;
}
890891
private void pp20DoUnpack(RandomAccessInputStream source, byte [] buffer) throws IOException
	{
		BitBuffer bitBuffer = new BitBuffer(source, (int)source.getLength()-4);
		source.seek(source.getLength()-1);
		int skip = source.read();
		bitBuffer.getBits(skip);
		int nBytesLeft = buffer.length;
		while (nBytesLeft > 0)
		{
			if (bitBuffer.getBits(1) == 0)
			{
				int n = 1;
				while (n < nBytesLeft)
				{
					int code = (int)bitBuffer.getBits(2);
					n += code;
					if (code != 3) break;
				}
				for (int i=0; i<n; i++)
				{
					buffer[--nBytesLeft] = (byte)bitBuffer.getBits(8);
				}
				if (nBytesLeft == 0) break;
			}
			
			int n = bitBuffer.getBits(2)+1;
			source.seek(n+3);
			int nbits = source.read();
			int nofs;
			if (n==4)
			{
				nofs = bitBuffer.getBits( (bitBuffer.getBits(1)!=0) ? nbits : 7 );
				while (n < nBytesLeft)
				{
					int code = bitBuffer.getBits(3);
					n += code;
					if (code != 7) break;
				}
			} 
			else
			{
				nofs = bitBuffer.getBits(nbits);
			}
			for (int i=0; i<=n; i++)
			{
				buffer[nBytesLeft-1] = (nBytesLeft+nofs < buffer.length) ? buffer[nBytesLeft+nofs] : 0;
				if ((--nBytesLeft)==0) break;
			}
		}
	}