rotate left integer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <stdlib.h>

typedef unsigned char byte;
using namespace std;
unsigned int rol32 ( unsigned int x, byte times );

int main(){
    int n=0x22face23;
    cout << "n= " << hex << n << endl;
    n = rol32 ( n,2 );
    cout << "n rol32 *2= ;" << endl << "n= " << hex << n << endl;
    //system( "pause" );
    return 0;
}

unsigned int rol32 ( unsigned int x, byte times ){
    byte temp=0;
    for( byte i=0; i<times; i++ ){
	    temp = x&31;
	    x <<= 1;
	    x |= ( temp<<1 );
    }
    return x;
}


The above code works only with rol32( x,1 ) and rol32( x,2 ).
If i type rol32( x,3 ) it would return a wrong value.

can you tell me where's the "bug" in rol32 ?
Neither line 20 nor 22 makes sense.

line 20 would be temp = x&80000000; // assuming you want to mask the most significant bit
line 22 would be if(temp) x |= 1;

line 18: unsigned int temp=0;
Last edited on
1
2
3
4
5
6
7
8
9
unsigned int rol32 ( unsigned int x, byte times ){
    unsigned int temp=0;
    for( byte i=0; i<times; i++ ){
     temp = x&0x80000000;
	    x <<= 1;
	    x |= ( temp>>31 );
    }
    return x;
}

Works!
Thanks :)
Last edited on
It's a bit strange behavior which may have something to do that the most significant bit may be interpreted as the signed bit

This should work:
1
2
3
	    temp = x>>31;
	    x <<= 1;
	    x |= temp;
Topic archived. No new replies allowed.