Reading the first n bits of a byte The way I am using this method assumes all data is byte-aligned, so I don't really care about the rest of the bits.

This method is written in an extension of BinaryReader which provides more methods when I'm reading binary data from files. The BinaryReader provided does not appear to support reading bits.

Is there a better way I could write this method? Also I'm not sure if there's a more direct way to build a bitmask so I did it the long way.

/* Returns the value of the first n bits. */
public byte ReadBits(byte n)
{
    byte val = base.ReadByte();
    byte sum = 0;
    for (int i = 0; i &lt; n; i++)
        sum += (byte)(val &amp; (1 &lt;&lt; i));
    return sum;
}


I am using .NET 3.5
I have not tested this that well. If anyone finds a bug, please let me know.

// Throws away the unused bits
public byte ReadFirstNBits(int n)
{
    Contract.Requires(n &gt;= 0 &amp;&amp; n &lt;= 8, "Code contract may be too slow for your needs");
    byte val = base.ReadByte();
    return val &gt;&gt; (8 - n);
}

// Throws away the unused bits
public byte ReadLastNBits(int n)
{
    Contract.Requires(n &gt;= 0 &amp;&amp; n &lt;= 8, "Code contract may be too slow for your needs");
    byte val = base.ReadByte();
    byte mask = (byte)((1 &lt;&lt; n) - 1);
    return val &amp; mask;
}


You can try this for yourself if you have a Python prompt:

&gt;&gt;&gt; a = 0b11001001 
&gt;&gt;&gt; a
201
&gt;&gt;&gt; a &gt;&gt; 4
12
&gt;&gt;&gt; a &gt;&gt; 5
6
&gt;&gt;&gt; a &gt;&gt; 3
25
&gt;&gt;&gt; a &gt;&gt; 6
3
&gt;&gt;&gt; a &gt;&gt; 2
&gt;&gt;&gt; for i in range(8): print bin(a &gt;&gt; i)

0b11001001
0b1100100
0b110010
0b11001
0b1100
0b110
0b11
0b1
&gt;&gt;&gt;