Re: Rotating through a four-bit nibble
"T. Alexander Popiel" <[email protected]>
| Newsgroups | gmane.comp.hardware.lego.robotics |
|---|---|
| Message-ID | <[email protected]> |
In message: <[email protected]> "Brian Davis" <[email protected]> writes: >I'm working in NQC, and I need to rotate the bit series in a 4-bit >(or 8-bit) nibble embedded in a 16-bit word. Annoying. Any suggestions? What are you optimizing for? Code clarity? Code speed? Code length? There are (to my knowledge) no truly pretty solutions to this. I would tend to go with: int rotbits(int input, int numbits, int offset, int rotdist) { int mask = (~((~0) << numbits)) << offset; int left = rotdist % numbits; int right = (numbits - left) % numbits; int temp = input & mask; return (input & ~mask) | (((temp << left) | (temp >> right)) & mask); } This generic solution is (of course) slower (and a bit harder to read) than a solution specifically tuned for a particular size, offset, and rotation distance... but it's 7 lines of code that can then be called wherever you need to do these sub-word manipulations. Depending on how good the NQC optimizer has gotten, it might even simplify down to the faster versions when given constants for the size and offset... - Alex