Definitely a WTF



  • No matter what the integer size, this would work a whole lot better:

    <FONT face="Courier New"><FONT size=2>unsigned long reverse(unsigned long theWord)
    {
        unsigned long result = 0;</FONT></FONT>

    <FONT face="Courier New"><FONT size=2>    int i;</FONT> </FONT>

    <FONT size=2>    for (i = 0; i < sizeof(theWord) * 8; ++i) {
            result <<= 1;
            result |= theWord & 0x01;
    </FONT><FONT size=2>
            theWord >>= 1;</FONT><FONT size=2>
        }</FONT>

    <FONT size=2>    return result;
    <FONT face="Courier New">}</FONT></FONT>

     



  • Whoops, didn't mean to create a new thread.  Too new to the forums...



  • Or you could replace the for-loop with a "while (theWord > 0)"



  • Aha, but you're assuming a char is 8 bits!  :p

    You want to use CHAR_BITS, which should be in the standard header limits.h.  (You know... just in case someone decides to run your code on a PDP-8...)



  • Oh, not again. Don't know what you're answering to, but you need 5*N =
    O(N) ALU operations in order to reverse order of 2^N bits, bytes or
    whatever. You used O(2^N). Even with loop unrolling it's 256 operations
    instead of 30. Go do your homework again.



    BTW "while (theWord > 0)" is incorrect.



  • No, you can't replace the for-loop with a "while (theWord > 0)".  If theWord = 1, the reversal would stop after one iteration.



  • Damn, you're right about the byte size.  Replace 8 with CHAR_BITS.



  • @kdean said:

    Damn, you're right about the byte size.  Replace 8 with CHAR_BITS.


    That's an even better WTF! The size of long depends on the architecture you are using, whereas the size of char depends on the character set of the application. Imagine a unicode (16 bit) aware application on a 32 bit architecture and you'll see what I mean ...


Log in to reply