Bit rotation question/challenge

burt invalid_email_address at cab.abc
Sat Jan 30 14:50:50 UTC 2021


On Saturday, 30 January 2021 at 14:17:06 UTC, Paul Backus wrote:
> On Saturday, 30 January 2021 at 13:30:49 UTC, burt wrote:
>> [...]
>>
>> Now I want to bit-rotate the array as if it is one big integer.
>
> You may find `std.bitmanip.BitArray` useful for this:
>
> http://phobos.dpldocs.info/std.bitmanip.BitArray.html

Thank you, this is indeed what I am looking for!

For future reference, this is how I implemented it:

```d
ubyte[n] rotateRight(size_t n)(ubyte[n] x, uint rotation)
{
     import std.bitmanip : BitArray;

     ubyte[n] x2;
     foreach (i, value; x) // have to swap because of endianness
         x2[n - 1 - i] = value;

     auto copy = x2;

     auto bitArray1 = BitArray(cast(void[]) x2[], n * 8);
     auto bitArray2 = BitArray(cast(void[]) copy[], n * 8);
     bitArray1 >>= rotation;
     bitArray2 <<= n * 8 - rotation;
     bitArray1 |= bitArray2;

     foreach (i, value; x2) // swap back
         x[n - 1 - i] = value;
     return x;
}

ubyte[4] x = [
     0b00011000,
     0b00100001,
     0b00010101,
     0b11110010,
];
writefln!"%(%8b,\n%)"(x.rotateRight(4));
```


More information about the Digitalmars-d-learn mailing list