Code:
#include <stdio.h>
// Function to rotate an unsigned int left or right
unsigned int rotate (unsigned int value, int n)
{
unsigned int result, bits;
//scale down the shift count to a defined range
if ( n > 0 )
n = n % 32;
else
n = -(-n % 32 );
if ( n == 0 )
result = value;
else if ( n > 0 ) { // left rotate
bits = value >> ( 32 -n );
//printf("\nIf n is a positive value, we rotate left\n");
//printf("Here is what is in bits %x\t\n",bits);
//printf("Here is what is in value %x\t\n", value);
//printf("Here is what is in n %d\t\n", n);
result = value << n | bits;
//printf ("Here is what result looks like: %x\t\n", result);
}
else { // right rotate
n = -n;
bits = value << ( 32 - n);
result = value >> n | bits;
}
return result;
}
unsigned int bitpat_search ( unsigned int number, unsigned int pattern, int numberBits )
{
unsigned int rotatedValue, bits, index = 0;
printf("\nHere is what is in bits %x", bits);
int i;
printf("\nHere is what is in number before it was rotated:%x\t", number);
rotatedValue = rotate (number, numberBits);
bits = rotatedValue;
printf ("\nHere is what is in number %x\t after it was rotated by %x bits", rotatedValue, numberBits);
for ( i=0; i<32; i++)
{
bits &= ~(0xfffffff8);
printf ("\nHere is what is in number after high order bits are set to zero %x\t", bits);
if (bits == pattern)
index = 32 - i;
rotatedValue = rotate (rotatedValue, numberBits);
bits = rotatedValue;
printf("\nHere is what is in number: %x\t and rotatedValue after rotation: %x\t ", number, rotatedValue);
}
//printf ("Here is what i went up to :%d", i);
return index;
}
/*******************************************Main Function*****************************************/
int main (void)
{
unsigned int w1 = 0xabcdef00u, w2 = 0xffff1122u;
unsigned int w3 = 0xe1f4, w4 = 0x5;
printf ("Here is what w4 looks like at the start %x", w4);
printf ("\nHere is what w3 looks like at the start %x", w3);
int result;
unsigned int rot3ff (unsigned int value, int n);
unsigned int bitpat_search ( unsigned int number, unsigned int pattern, int numberBits );
result = bitpat_search (w3, w4, 3);
//printf ("%x\n", rotate (w1, 8));
//printf ("%x\n", rotate (w1, -16));
//printf ("%x\n", rotate (w2, 4));
//printf ("%x\n", rotate (w2, -2));
//printf ("%x\n", rotate (w1, 0));
//printf ("%x\n", rotate (w1, 44));
printf ("Here is the index : %d\n", result);
return 0;
}
Just an update; I figured it out. It seems to work. I just had not printed out the match.