@@ -144,7 +144,7 @@ public override void Flush() { } // NOP
144
144
private byte ReadByteMisaligned ( )
145
145
{
146
146
int mod = ( int ) ( BitPosition & 7 ) ;
147
- return ( byte ) ( ( target [ ( int ) Position ++ ] >> mod ) | ( target [ ( int ) Position ] << ( 8 - mod ) ) ) ;
147
+ return ( byte ) ( ( target [ ( int ) Position ] >> mod ) | ( target [ ( int ) ( BitPosition += 8 ) >> 3 ] << ( 8 - mod ) ) ) ;
148
148
}
149
149
/// <summary>
150
150
/// Read an aligned byte from the buffer. It's recommended to not use this when the BitPosition is byte-misaligned.
@@ -224,6 +224,7 @@ public override void SetLength(long value)
224
224
if ( value < 0 ) throw new IndexOutOfRangeException ( "Cannot set a negative length!" ) ;
225
225
if ( value > Capacity ) Grow ( value - Capacity ) ;
226
226
BitLength = ( ulong ) value << 3 ;
227
+ BitPosition = Math . Min ( ( ulong ) value << 3 , BitPosition ) ;
227
228
}
228
229
229
230
/// <summary>
@@ -269,7 +270,7 @@ public void WriteBit(bool bit)
269
270
{
270
271
if ( BitAligned && Position == target . Length ) Grow ( 1 ) ;
271
272
int offset = ( int ) ( BitPosition & 7 ) ;
272
- ulong pos = BitPosition >> 3 ;
273
+ long pos = Position ;
273
274
++ BitPosition ;
274
275
target [ pos ] = ( byte ) ( bit ? ( target [ pos ] & ~ ( 1 << offset ) ) | ( 1 << offset ) : ( target [ pos ] & ~ ( 1 << offset ) ) ) ;
275
276
UpdateLength ( ) ;
@@ -810,7 +811,7 @@ private void _WriteMisaligned(byte value)
810
811
{
811
812
int off = ( int ) ( BitPosition & 7 ) ;
812
813
int shift1 = 8 - off ;
813
- target [ Position + 1 ] = ( byte ) ( ( target [ Position + 1 ] & ( 0xFF >> off ) ) | ( value >> shift1 ) ) ;
814
+ target [ Position + 1 ] = ( byte ) ( ( target [ Position + 1 ] & ( 0xFF << off ) ) | ( value >> shift1 ) ) ;
814
815
target [ Position ] = ( byte ) ( ( target [ Position ] & ( 0xFF >> shift1 ) ) | ( value << off ) ) ;
815
816
816
817
BitPosition += 8 ;
0 commit comments