CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2002
    Posts
    2

    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


  2. #2
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    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

  3. #3
    Join Date
    Jan 2002
    Posts
    2

    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



  4. #4
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    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
  •  





Click Here to Expand Forum to Full Width

Featured