|
-
January 8th, 2002, 12:13 PM
#1
reverse bit order
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
-
January 8th, 2002, 01:26 PM
#2
Re: reverse bit order
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
-
January 8th, 2002, 02:24 PM
#3
Re: reverse bit order
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
-
January 9th, 2002, 05:40 AM
#4
Re: reverse bit order
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|