After seeing this thread, I was trying to think of how I would pack a 3D rotation into a fixed number of bits, for instance to store animation data. I wrote a little piece of code with the result and I think it's neat enough to share.

The idea is to encode a unit-length quaternion in a manner analogous to cube mapping, but with one extra dimension and taking advantage of the property that a sign flip doesn't change which rotation is being represented.

One can think of cube mapping as consisting of an encoding of points in a sphere by first indicating which coordinate has largest absolute value and what sign it has (i.e., which of the 6 faces of the axis-aligned cube the point projects to) and then the remaining coordinates divided by the largest one (i.e., what point of the face the point projects to).

In our case, we don't need to encode the sign of the largest component, so we only need to use 2 bits to encode what the largest component is, and we can use the remaining bits to encode the other three components.

I think 32 bits is probably good enough for animation data in a game, and it's convenient that 30 is a multiple of 3, so it's easy to encode the other components. Actually, even if we didn't have that convenience, it wouldn't be a big deal to use a resolution that is not a power of 2, but some integer divisions would be involved in the unpacking code.

Here's the code, together with a main program that generates random rotations and measures how bad the dot product between the original and the packed and unpacked gets (the dot product seems to be > 0.999993, although I haven't made a theorem out of it):

A quaternion with 810[/stealthedit] bites per component runs into the following issues:

1) You're optimizing for a problem you don't even know you have.2) Extracting bytes from a register may well slow things down significantly (where significantly = no real increase).3) If you're so low on memory you can't spare 128 bits (even on cell phones, 8,589,934,592 bits is easy) for animations, you've probably got other, more important problems.4) Rotation might be slightly choppy.

So, in short:

1) Make sure you know what the problem actually is before you try to fix it.2) At least static-test your solution concepts.3) Don't optimize where you don't need to.4) Something to check.