I am looking for a method to reverse the bytes in a character array.I also need to reverse the individual bits of the bytes being swapped before positioning them in the right place. for example say I have a char arr[1000] whose arr[0] = 00100011 and arr[999] = 11010110, I want to swap arr[0] and arr[999] and in addition reverse the bits in each of them. so the output would be arr[999]= 11000100 ( reversed bits of arr[0]) and arr[0] = 01101011 (reversed bits of arr[999]).
I have some code to do the bit reversal inside a byte :
static char reverseByte(char val)
{
char result = 0;
int counter = 8;
while (counter-- < 0)
{
result <<= 1;
result |= (char)(val & 1);
val = (char)(val >> 1);
}
return result;
}
But this would mean running an outer loop to do the byte swap and then running the above small loop for each byte inside i.e 1000 in the above case. Is this the right approach ? Is there a better way to achieve this ? Any help would be greatly appreciated.
O(n)
time and space (on the order of bits). Now, coefficients can probably be better in some cases than others. – RageD