/// <summary> /// Reads the given number of bits into the value and returns whether the stream could be read from or not. /// </summary> /// <param name="value">The value of the read bits.</param> /// <param name="bits">The number of bits to read.</param> /// <returns>Whether the stream could be read from or not.</returns> public bool ReadBits(out byte value, BitNum bits) { if (BitPosition == BitNum.MaxValue && bits == BitNum.MaxValue) { var readByte = stream.ReadByte(); value = (byte)(readByte < 0 ? 0 : readByte); currentByte = value; return(!(readByte < 0)); } value = 0; for (byte i = 1; i <= bits; ++i) { if (BitPosition == BitNum.MaxValue) { var readByte = stream.ReadByte(); if (readByte < 0) { return(i > 1); } currentByte = (byte)readByte; } advanceBitPosition(); value |= getAdjustedValue(currentByte, BitPosition, (BitNum)i); } return(true); }
private BitNum(byte value, bool overide) { if (!overide) { this = new BitNum(value); } else { this.value = value; } }
private static byte getAdjustedValue(byte value, BitNum currentPosition, BitNum targetPosition) { value &= currentPosition.GetBitPos(); if (currentPosition > targetPosition) { return((byte)(value >> (currentPosition - targetPosition))); } else if (currentPosition < targetPosition) { return((byte)(value << (targetPosition - currentPosition))); } else { return(value); } }
/// <summary> /// Writes the given number of bits from the value. /// </summary> /// <param name="value">The value to write from.</param> /// <param name="bits">The number of bits to write.</param> public void WriteBits(byte value, BitNum bits) { if (BitPosition == BitNum.MaxValue && bits == BitNum.MaxValue) { stream.WriteByte(value); currentByte = 0; return; } for (byte i = 1; i <= bits; ++i) { advanceBitPosition(); currentByte |= getAdjustedValue(value, (BitNum)(9 - i), (BitNum)(9 - BitPosition)); // [CHANGE] if (BitPosition == BitNum.MaxValue) { stream.WriteByte(currentByte); currentByte = 0; } } }
public void WriteBits(byte b, BitNum bits) { _bitStream.WriteBits(b, bits); }