Bits in reverse order in BitArray

Steven Schveighoffer schveiguy at yahoo.com
Mon Jul 4 11:34:59 PDT 2011


On Mon, 04 Jul 2011 14:03:35 -0400, Christian Manning  
<cmanning999 at gmail.com> wrote:

> Hi, when I populate a BitArray using .init, the bits are in reverse  
> order, although the bytes are in the correct order.
> eg:
>
> import std.stdio,std.bitmanip;
>
> void main() {
>      ubyte[] arr = [130,56,43,2];
>
>      BitArray ba;
>      ba.init(cast(void[])arr,32);
>      foreach(b; ba)
>         write(cast(ubyte) b); //bits in each byte reversed
>                               //01000001000111001101010001000000
>      writeln();
>
>      ba.init(cast(void[])arr.reverse,32);
>      foreach(b; ba.reverse)
>         write(cast(ubyte) b); //bits printed in intended order
>                               //10000010001110000010101100000010
>      writeln();
> }
>
> Why does this happen?

What exactly are you expecting?  In other words, when using the void[]  
version of init, you are specifying the exact memory to use, which implies  
you know how BitArray's internals work.  If you create a BitArray by  
adding bits to the BitArray, then it's internal storage doesn't matter to  
you, it can store however it wants.

I'd guess the most logical reason to store the bits in reverse order would  
be for performance.  Not sure what the merits are, but typically, it's  
faster to access and manipulate the 0 bit than some arbitrary bit.

-Steve


More information about the Digitalmars-d-learn mailing list