26818 total geeks with 3504 solutions
Recent challengers:
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
MaxMouse
It's Friday... That's good enough for me!
CodeX
non stop lolz here but thats soon to end thanks to uni, surely the rest of the world is going good?
stabat
how things are going guys? Here... boring...
CodeX
I must be going wrong on the password lengths then, as long as it was done on ECB
MaxMouse
lol... the key is in hex (MD5: of the string "doit" without the "'s) and is in lower case. Maybe i should have submitted this as a challenge!

Donate
Donate and help us fund new challenges
Donate!
Due Date: Apr 30
April Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
LOHAN and the
amazing technicolor
spaceplane
R.I.P. LADEE: Probe
smashes into lunar
surface at 3,600mph
Judge halts spread
of zombie Nortel
patents to Texas in
Google trial
Record labels sue
Pandora over
vintage song
royalties
True optical zoom
coming to HTC
smartphone cameras
Google lets wannabe
Glass Explorers
ADMIRE THEMSELVES
in their own
mirrors
Liftoff! SpaceX
Falcon 9 lifts
Dragon on third
resupply mission to
ISS
Leaked photos may
indicate slimmer
next-generation
iPad
Reddit users
discover iOS
malware threat
Edward Snowden on
his Putin TV
appearance: "Why
all the criticism?"
Slashdot
Closing Surgical
Incisions With a
Paintbrush and
Nanoparticles
Preventative
Treatment For
Heartbleed On
Healthcare.gov
New "Google" For
the Dark Web Makes
Buying Dope and
Guns Easy
3 Former
Astronauts:
Earth-Asteroid
Collisions Are a
Real But
Preventable Danger
Ask Slashdot:
Hungry Students,
How Common?
Google"s New Camera
App Simulates
Shallow Depth of
Field
Beer Price Crisis
On the Horizon
Heartbleed Used To
Bypass 2-Factor
Authentication,
Hijack User
Sessions
Russia Writes Off
90 Percent of North
Korea Debt
The Design Flaw
That Almost Wiped
Out an NYC
Skyscraper
Article viewer

ROL/ROR in C



Written by:dimport
Published by:Nightscript
Published on:2003-06-21 07:19:46
Topic:C
Search OSI about C.More articles by dimport.
 viewed 30751 times send this article printer friendly

Digg this!
    Rate this article :
Here is a tips for anyone wondering about how to do ROR, ROL (rotate) ASM instructions inC code. For whom that don't know exactly what it is, here's an explanation...

ROL: Rotate left. (i.e. shift bits left and append them to right)

For example:
10010110

ROL of 3:10110100(-100-)10110(+100+)
ROR: Rotate right. (i.e. shift bits right and append them to left)

Same example:
10010110

ROR of 3:11010010(+110+)10010(-110-)

I hope you understand well. So here''s how to rotate the "char" type (8 bits) in C:

Here a simple example:
z = rol8(65, 3); // 01000001b ROL 3 -> 00001010b == 10</td></tr></table>

So, this is that for now. Please don't be shy to add your comments.
--
Sphinz

This article was originally written by sphinz

Did you like this article? There are hundreds more.

Comments:
krashnburn
2004-03-03 17:26:27
on my pc your explanation is lost amongst misformated html.
I was flored when i had to write my own rotate functions for java.
in c++ though its not necesary
__asm
{
mov eax,MyVar;
rol eax,8;
mov MyVar,eax;
}
adsafde
2004-04-22 19:21:57
krashnburn's code works on a 80x86 PC using Microsoft C++, but if it's preferable to write code that works on other platforms, you still have to write your own rotate functions. Note that his code will work in C if you're using Microsoft C++, too.

Basically, here's some simple rotate code:

int WORD_LENGTH;
int rol(int value, int places)
{
  return (value<<places)|(value>>(WORD_LENGTH-places);
}

int ror(int value, int places)
{
  return (value>>places)|(value<<WORD_LENGTH-places);
}


In case you're wondering, here's one way to calculate WORD_LENGTH:
void CALC_WORD_LEN(void)
{
  unsigned int x=~0;
  int i=1;
  while(x>>=) i++;
}

adsafde
2004-05-04 14:45:47
Oops... I forgot to put the line WORD_LENGTH=i; into the CALC_WORD_LEN() function (it goes at the end, after the while loop).
sefo
2004-06-18 07:55:08
adsafde, is there not an error in the while loop?
while(x>>=)

void CALC_WORD_LEN(void)
{
unsigned int x=~0;
int i=1;
while(x>>=?) i++;
WORD_LENGTH=i;
}
lonetech
2005-05-03 17:53:25
Besides that, you're not very likely to want a rotation if you don't know its size. Feel free to use uint16_t and friends from stdint.h.
Isaac
2005-11-29 06:34:26
I think there is an easier way to calculate WORD_LEN
#define WORD_LEN(w) (8*sizeof(w))

or either
#define WORD_LEN(w) (sizeof(w)<<3)

Isaac
2005-12-02 16:43:56
The code for ror
int ror(int value, int places)
{
  return (value>>places)|(value<<WORD_LENGTH-places);
}

works fine for value>=0, but if value<0 it fails, since value is a signed int, value>>places
inserts the sign bit on the left.
Fully (I hope) functional code should be
#define WORD_LENGTH (8*sizeof(value))
int rol(unsigned value, int places)
{
  return (value<<places)|(value>>(WORD_LENGTH-places);
}

int ror(unsigned int value, int places)
{
  return (value>>places)|(value<<WORD_LENGTH-places);
}
#undef WORD_LENGTH

Anonymous
2008-06-10 08:02:34
For java:

Integer.rotateLeft(int i, int distance)
Integer.rotateRight(int i, int distance)

since 1.5 :)
Anonymous
2009-04-22 14:37:17
I forgot to put the line WORD_LENGTH=i; into the CALC_WORD_LEN() function (it goes at the end, after the while loop). online game
godfatha
2009-06-13 03:01:34
The thread is old as hell, but i was looking for the same thing as inline assembler function in gcc. here is my solution, maybe it helps someone:

#include <stdio.h>
#include <inttypes.h>

__inline__ rol(uint32_t operand, uint8_t width) {
  __asm__ __volatile__ ("rol %%cl, %%eax"
                        : "=a" (operand)
                        : "a" (operand), "c" (width)
                        );
}

int main ()
{
    uint32_t testint = 0x80000000;
    testint = rol(testint,1);
    printf("%X\n", testint);
    return 0;
}



Short expl.: function rol receives two ints (one 32 bit, one 8), the 32 bit var is stored in EAX ("a"), the 8 bit in the low part of ECX (CL) ("c"). rol/ror etc can receive a constant or memory or register as rotation width, if its a register it has to be CL, thats why the code is like that. Now rol EAX CL bits wide and return EAX (=a). Since its a function, the to be rotated var has to be reassigned with the return value of rol().

If its done inline with no extra function, the var neednt to be reassigned:

#include <stdio.h>
#include <inttypes.h>

int main ()
{
    uint32_t testint = 0x80000000;
    uint8_t width = 3;
    //testint = rol(testint,1);
    
    __asm__ __volatile__ ("rol %%cl, %%eax"
        : "=a" (testint)
        : "a" (testint), "c" (width)
    );
    
    printf("%X\n", testint);
    return 0;
}


-Tim
jirka77
2009-10-26 00:52:43
Hello,

I have further improved the code above. ror/rol can use memory directly. The code bellow is for X64 (AMD) architecture:

#define ror(i,by) \
    __asm__ ( \
            "rorq %b1,%q0"\
            :"+g" (i) \
            :"Jc" (by) )

/*no clobber list*/
#define rol(i,by) \
    __asm__ ( \
            "rolq %b1,%q0"\
            :"+g" (i) \
            :"Jc" (by) )


int main() {
uint8_t a=1;
uint64_t b=1;

ror(b,a);
printf("%0llX\n",b);
rol(b,a);
printf("%0llX\n",b);

ror(b,1);
printf("%0llX\n",b);
rol(b,1);
printf("%0llX\n",b);

return 0;
}
[/code]

Please notice that I'm using
+mr => + means that it's used for both input&output
mr means that it can be memory or register
Jc => means either integer in range 0..63 or c register

%b1,%0
%b1 => width of the first operand is 8 bits.
rorq => means that we are working with m64 (64 bit memory) - Important for memory arguments.

ror(b,a);
translates into
rorq %cl,-1144(%rbp)

while
ror(b,1);
translates into
rorq $1,-1144(%rbp)


So the compiler can either copy number to be rotated into register or leave it in memory. It can also decided if number of bits to be shifted needs to be copied into cl register or it's already known during the compilation time.

Have fun with inline asm.

Jiri
jirka77
2009-11-19 23:54:00
Hi Tim,

there is one mistake in your code - missing return statement. Your code works well as long as the function is NOT INLINED (gcc without any optimization enabled). When you force gcc to really inline the function (gcc -O1) it does not work anymore. I have tested it on operand 0x1. ROL(0x1,1) should give 0x2.
gcc -O1 -o strange strange.c && strange
D301BC98
gcc -o strange strange.c && strange
2

Actually, it prints random number - the value of esi register.

Correct code is bellow:
__inline__ uint32_t ror32f(uint32_t operand, uint8_t width) {
  __asm__ __volatile__ ("rorl %b1, %0"
                        : "+mr" (operand)
                        : "Jc" (width)
                        );
    return operand;
}

Just my 2 cents.

Jiri
Anonymous
2010-12-03 13:40:11
FFS I DUN GETZ IT!
ObatAsamUrat
2011-06-16 07:25:38
That is certainly a number of peak performance goods. Couldn't know that will ideas may be this specific various. Appreciate your each of the eagerness to make available this sort of information below.
obat asam urat
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
amisauv
Creating a Lexical Analyzer in C on Tue 9th Dec 11am
#include<stdio.h> #include<string.h> #include<conio.h> #include<ctype.h> /*************************************** ************************* Functions prototype. **************************************** *************************/ void Open_File(
amisauv
Controling digital circuit through computer on Tue 9th Dec 10am
this code access the lpt port.here only 4 of the total 8 pins are used but can be modified for full 8 pins.it has a complete GUI with mouse & keyboard interactive control panel.works well in win98, but not in winxp. #include<stdio.h> #include<conio.
amisauv
/* Computerised Electrical Equipment Control */ /* PC BASED DEVICE CONTROLLER * on Tue 9th Dec 10am
#include<stdio.h> #include<conio.h> #include<dos.h> void main() { void tone(void); int p=0x0378; char ex={"Created By Mrc"}; int j; char ex1={"For Further Details & Improvements"}; int k; char ex2={"Contact : E-mail : anbudan
amisauv
Calendar Program on Tue 9th Dec 10am
This program prints Weekdays of specified date. It even prints calendar of a given year too. /*Ccalendar library*/ #include<stdio.h> #include<string.h> #include<conio.h> int getNumberOfDays(int month,int year) { switch(month) { case
amisauv
Calculator: on Tue 9th Dec 10am
#include"graphics.h" #include"dos.h" #include"stdio.h" #include"math.h" union REGS i,o; char text={ "7","8","9","*","4","5","6","/","1","2", "3","+","0","00",".","-","M","M+", "M-","+/-","MR","MC","x^2","sr","OFF","A C","CE","="}; int s=0,k=0,pass
amisauv
INFECTED CODES WRITTEN IN C\C++ on Tue 9th Dec 10am
This is a simple code that changes system time and date. It is written using c/c++ but can be easily converted to java. #include "stdio.h" #include "process.h" #include "dos.h" int main(void) { struct date new_date; struct date old_date; s
amisauv
A C programme which can print the file name it is kept in on Tue 9th Dec 9am
amisauv
BOOTSECTOR EDITOR: on Tue 9th Dec 9am
Code : /*program to save the partion table of your hard disk for future use. it will save your partition table in a file partition.dat */ #include<stdio.h> #include<bios.h> #include<conio.h> #include<stdlib.h> #include<ctype.h> void main () {
amisauv
BLINKING STAR : on Tue 9th Dec 9am
#include<conio.h> #include<graphics.h> #include<stdlib.h> #include<dos.h> void main() { int gdriver=DETECT,gmode; int i,x,y; initgraph(&gdriver,&gmode,"e: cgi"); while(!kbhit()) { x=random(640); y=random(480); setcolor
amisauv
// To print semicolons using C programming without using semicolons any where i on Tue 9th Dec 9am
// To print semicolons using C programming without using semicolons any where in the C code in program. // #include<stdio.h> #include<conio.h> void main() { char a; a=59; if(printf("%c",a)){} getch();

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
BSD sockets API by skrye

This is a test of your knowledge of the BSD socket interface
C Programming by keoki

This test is aimed at a C programmer that is at an intermediate level.


     
Your Ad Here
 
Copyright Open Source Institute, 2006