Mail Archives: djgpp/1999/02/01/19:23:39
anarko wrote:
>
> hi, i've only coded ansi C for 3 days or so, but i've coded other
> programming languages before, so i'm learning quick.
>
> one thing i want to do is rotate a char value's bits, like
> the x86 assembly instruction ROR/ROL does.
> is this possible with an operator, or do i have to use inline
> assembly for that?
#include <limits.h> /* for CHAR_BIT */
#define CHAR_MASK ((1 << CHAR_BIT) - 1) /* 0xff */
unsigned char rol(unsigned char x, int count)
{
return ((x << count) | (x >> (CHAR_BIT - count)) & CHAR_MASK;
}
unsigned char ror(unsigned char x, int count)
{
return ((x >> count) | (x << (CHAR_BIT - count)) & CHAR_MASK;
}
You might do better to define these as macros; this is left as an
exercise for the reader. :) In fact, when compiling this algorithm, GCC
will in some cases optimize and generate the appropriate rotate
instruction (!).
--
Nate Eldredge
nate AT cartsys DOT com
- Raw text -