1ntgr - 1 year ago 91
C++ Question

Rotate Left by x bits in C++

I'm trying to write a ROL function in C++ and have seen a number of questions relating to it. My knowledge is such that I don't really understand how it works.

I am using the below code

``````#include<stdio.h>
#define INT_BITS 32
using namespace std;
int leftRotate(int n, unsigned d){ //rotate n by d bits
return (n << d)|(n >> (INT_BITS - d));
}

int main() {
int n = 0xa3519eba;
int d = 0x0f;
printf("Left rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
}
``````

I'm expecting a result of 0xcf5d51a8, but instead what I get is signed 0x2e58.

Any direction on where I'm going wrong would be much appreciated.

Funny things happen when you try to do bit math on a signed value, because of the sign bit.

``````#include<stdio.h>
#define INT_BITS 32

int leftRotate(unsigned n, unsigned d){ //rotate n by d bits
return (n << d)|(n >> (INT_BITS - d));
}

int main() {
unsigned n = 0xa3519eba;
unsigned d;

for( d = 0; d < 32; d += 4 )
printf("Left rotation of 0x%.8X by %d is 0x%.8X\n", n, d, leftRotate(n, d));
}
``````

Output:

``````Left rotation of 0xA3519EBA by 0 is 0xA3519EBA
Left rotation of 0xA3519EBA by 4 is 0x3519EBAA
Left rotation of 0xA3519EBA by 8 is 0x519EBAA3
Left rotation of 0xA3519EBA by 12 is 0x19EBAA35
Left rotation of 0xA3519EBA by 16 is 0x9EBAA351
Left rotation of 0xA3519EBA by 20 is 0xEBAA3519
Left rotation of 0xA3519EBA by 24 is 0xBAA3519E
Left rotation of 0xA3519EBA by 28 is 0xAA3519EB
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download