www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/02/01/19:23:39

Sender: nate AT cartsys DOT com
Message-ID: <36B644CF.971124A@cartsys.com>
Date: Mon, 01 Feb 1999 16:20:31 -0800
From: Nate Eldredge <nate AT cartsys DOT com>
X-Mailer: Mozilla 4.08 [en] (X11; I; Linux 2.0.36 i586)
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: can i do bit rotation in C?
References: <19990131193159 DOT 13889 DOT 00002566 AT ng142 DOT aol DOT com> <11125 DOT 990201 AT flashback DOT net>
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019