Best way in D2 to rotate a ubyte[4] array
Jonathan M Davis
jmdavisProg at gmx.com
Wed Mar 9 15:55:50 PST 2011
On Wednesday, March 09, 2011 15:35:29 Kai Meyer wrote:
> On 03/09/2011 03:41 PM, Tom wrote:
> > What is the most efficient way of implement a rotation of ubyte[4] array?
> >
> > By rotation I mean: rotateRight([1, 2, 3, 4]) -> [4, 1, 2, 3]
> >
> > TIA,
> > Tom;
>
> I don't know of anything more efficient than:
> ubyte[4] bytes = [1,2,3,4];
> bytes = bytes[$-1] ~ bytes[0..$-1]; // Rotate left
I'm stunned that this works. I'd even consider reporting it as a bug. You're
concatenating a ubyte[] ont a ubyte...
> bytes = bytes[1..$] ~ bytes[0]; // Rotate right
You're concatenating a ubyte onto a slice of the array (so it's ubyte[] instead
of ubyte[4]). That will result in a temporary whose value will then be assigned
to the original ubyte[4].
> Both static arrays and dynamic arrays (ubyte[] bytes = [1,2,3,4];)
> perform about the same between 1 and 10 milling rotations in either
> direction. I think a temporary array might be created for the rhs, and
> then have the values of the rhs array copied to the lhs array, but I
> don't know. With static arrays, I'm not sure there would be a way to get
> around it with out at least a temporary value for the one that's moving
> between the first and last positions.
Honestly, given that this is 4 ubytes, I would fully expect that the fastest way
to do this would involve casting it to a unit and shifting it - something along
the lines of what Bearophile suggested. I'd be _very_ suprised if this
implementation were faster, since it involves creating a temporary array.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list