Hi,
I have this piece of code, just testing the set and mask functions. Here I have a original hex string ABC and I want to put it into result in reverse. I have the mask as 0xF (1111) and take each letter at a time and set it in result, then I left shift the result var bits 4 places to make room for the next letter and right shift the original var 4 bits to get at the next letter (4 bits). However running this code does not turn ABC into CBA but rather F. Going through the code again and again - I can't see what's wrong with it. Can you? The vars are unsigned ints (no 2 complement here).
Code:
int main(void)
{
unsigned int original = 0xABC;
unsigned int result = 0;
unsigned int mask = 0xF; /* rightmost 4 bits 1111 F is 16 over 4 bits */
printf("\nOriginal = %X", original);
/* Insert first digit in result */
result |= original&mask; /* put right 4 bits from original in result */
/* Get second digit */
original >>= 4; /* shift original right 4 places */
result << 4; /* make room by shifting left 4 places */
result |= original&mask; /* put right 4 bits from original in result */
/* Get third digit */
original >>= 4;
result << 4;
result |= original&mask; /* reminder - | sets and & tests */
printf("\t result = %X\n", result);
return 0;
}