Click to See Complete Forum and Search --> : reverse bit order


Jaime Guevara
January 8th, 2002, 11:13 AM
How do I reverse the bit order for a 16 bit word? For example, if a number is represented as 0011 1011 1010 1110 then it has to be written to a file with the least significant bit first as 0111 0101 1101 1100. Also I'm devleloping in C.

Thanks,
Jaime Guevara

NMTop40
January 8th, 2002, 12:26 PM
Here is one way

unsigned short BitReverse( unsigned short x )
{
unsigned short xReverse = 0;
for ( int cBits = 16; cBits--; )
{
xReverse <<= 1;
xReverse |= (x&1);
x >>= 1;
}
return xReverse;
}




Note in particular your function should use unsigned variables. It assumes that short is at least 16 bits, not exactly that length.


The best things come to those who rate

Jaime Guevara
January 8th, 2002, 01:24 PM
Thanks for the tip.

Since I need to transmit that 16-bit word serially in that order should I write the the data as:

b = (BYTE)(reversedWord >> 8); //Upper Byte
WriteFile(handle, &b, 1, &numBytesWritten, NULL);
b = (BYTE)reversedWord & 0x000000ff; // lower byte
WriteFile(handle, &b, 1, &numBytesWritten, NULL);






Thanks Again,
Jaime Guevara

NMTop40
January 9th, 2002, 04:40 AM
sending it one byte at a time like that would ensure a standard byte order on all platforms, except that of course WriteFile is not a standard command. fwrite() is the ANSI-standard in C.

You could write a reverseByte function although when I had to do this in a project last year I created a table and looked up the reverse on the table.

I did that by writing a one-only reverseByte function which wrote the output to a file in hexadecimal and then used that output in the code. This my program wrote something like

0x00,
0x80,
0x40,
0x60
...

then on any platform you can convert a word as follows:

void ReverseWord[ unsigned char[2] target, unsigned short source )
{
target[0] = ReverseByte[(source >> 8) & 0xff];
target[1] = ReverseByte[ source & 0xff ];
}





This is assuming you are implementing ReverseByte as a const array, not as a function. (If a function, simply use ( ) instead of [ ] )


The best things come to those who rate