How to reverse bits...

Chris Hind Genly chris at genly.UUCP
Tue Aug 14 09:49:26 AEST 1990


>In article <487 at demott.COM> kdq at demott.COM (Kevin D. Quitt) writes:
>In article <1990Aug13.185757.3236 at sti.fi> ttl at sti.fi (Timo Lehtinen) writes:
>>This might be trivial, but here goes...
>>What's the most optimal way to reverse the bits in an unsigned char,
>>i.e. change from MSB to LSB ordering ?
>>
>    If by optimal, you mean fastest with the least code, try a char[256]
>array with the bits already reversed.  You just look 'em up.  (It may be
>gross, but the table+code is often smaller than the conversion code). 

You'll need something to generate the table.  Here is a small routine
to do it.  On a mini-super, where the alus are much faster than
memory, this routine may actually be faster than a table lookup.  For
a pc, a table lookup is faster.

/*
 * A bit reverse for 8 bits.
 */
unsigned char bitrev(i)
unsigned char i;
{
    i = (i & 0x0f) <<  4  |  (i & 0xf0) >>  4;
    i = (i & 0x33) <<  2  |  (i & 0xcc) >>  2;
    i = (i & 0x55) <<  1  |  (i & 0xaa) >>  1;
    
    return i;
}

       *                        *                        *
                                                            \|/
               *           _______                         --O--
                      ____/ KC1VP \____        *            /|\
 *      _____________/  (203) 389-8680 \_______________
 ______/  95 Fountain Terr., New Haven, CT, USA, 06515 \_______
/ Chris Hind Genly    chris at genly.uucp   uunet!hsi!genly!chris \
----------------------------------------------------------------



More information about the Comp.lang.c mailing list