private Int48(long value) { this.b0 = (byte)(value & 0xFF); this.b1 = (byte)((value >> 8) & 0xFF); this.b2 = (byte)((value >> 16) & 0xFF); this.b3 = (byte)((value >> 24) & 0xFF); this.b4 = (byte)((value >> 32) & 0xFF); this.b5 = (byte)((value >> 40) & 0x7F); this.sign = (byte)((value >> 47) & 1); }
/// <summary> /// Write a sequence of bits into the stream /// </summary> /// <param name="bits"><see cref="Bit"/>[] to write</param> /// <param name="offset">Offset to begin bit writing</param> /// <param name="length">Number of bits to write</param> public void WriteBits(Bit[] bits, int offset, int length) { for (int i = offset; i < length; i++) { WriteBit(bits[i]); } }
/// <summary> /// Write a sequence of bits into the stream /// </summary> /// <param name="bits"><see cref="Bit"/>[] to write</param> /// <param name="length">Number of bits to write</param> public void WriteBits(ICollection<Bit> bits, int length) { Bit[] b = new Bit[bits.Count]; bits.CopyTo(b, 0); for (int i=0;i< length;i++) { WriteBit(b[i]); } }
/// <summary> /// Writes a bit in the current position /// </summary> /// <param name="data">Bit to write, it data is not 0 or 1 data = data & 1</param> public void WriteBit(Bit data) { stream.Seek(offset, SeekOrigin.Begin); byte value = (byte)stream.ReadByte(); stream.Seek(offset, SeekOrigin.Begin); if (!MSB) { value &= (byte)~(1 << bit); value |= (byte)(data << bit); } else { value &= (byte)~(1 << (7 - bit)); value |= (byte)(data << (7 - bit)); } if (ValidPosition) { stream.WriteByte(value); } else { if (AutoIncreaseStream) { if (ChangeLength(Length + (offset - Length) + 1)) { stream.WriteByte(value); } else { throw new IOException("Cannot write in an offset bigger than the length of the stream"); } } else { throw new IOException("Cannot write in an offset bigger than the length of the stream"); } } AdvanceBit(); stream.Seek(offset, SeekOrigin.Begin); }
/// <summary> /// Read from current position the specified number of bits /// </summary> /// <param name="length">Bits to read</param> /// <returns><see cref="Bit"/>[] containing read bits</returns> public Bit[] ReadBits(int length) { Bit[] bits = new Bit[length]; for(int i=0;i< length; i++) { bits[i] = ReadBit(); } return bits; }
/// <summary> /// Apply a xor operator on the current stream and bit position and advances one bit position /// </summary> /// <param name="bit">Bit value to apply xor</param> public void BitXor(Bit x) { if (!ValidPosition) { throw new IOException("Cannot read in an offset bigger than the length of the stream"); } Seek(offset, bit); Bit value = ReadBit(); ReturnBit(); WriteBit(x ^ value); }