Thread: Variable rotate

  1. #1
    Registered User
    Join Date
    Jun 2015
    Posts
    14

    Exclamation Variable rotate

    Is it possible to rotate whole variable?

    Something likae 0101 0101 0101 0101 -> 1010 1010 1010 1010?

    If yes, how? I found so many examples on how to rotate few bits but not the whole variable?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Lazar View Post
    I found so many examples on how to rotate few bits but not the whole variable?
    whole variable is also a few bits ... like 8 * sizeof variable
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Bit-shifting is easily done with bit-wise operators.

    There are no native C operators that do a rotate, but you can easily roll your own function to do this. This just requires a bit check, a single shift, and (if necessary) a bit set ... repeated as many times as needed.

  4. #4
    Registered User
    Join Date
    Jun 2015
    Posts
    4
    Code:
    unsigned short rotate( unsigned short value )
    {
        return (value << 1) | ((value >> 15) & 1);
    }

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sd_sundevil View Post
    Code:
    unsigned short rotate( unsigned short value )
    {
        return (value << 1) | ((value >> 15) & 1);
    }
    Instead of the magic number 15, it might be better to write: (sizeof(value) * CHAR_BIT - 1)
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to rotate a 64-bit BitBoard?
    By cyberfish in forum C++ Programming
    Replies: 10
    Last Post: 05-03-2008, 04:26 AM
  2. Do I really need to rotate?
    By JimJoyce in forum Game Programming
    Replies: 13
    Last Post: 02-24-2005, 04:04 PM
  3. How to rotate
    By cfrost in forum Windows Programming
    Replies: 5
    Last Post: 07-15-2004, 10:08 AM
  4. rotate string
    By cit in forum C Programming
    Replies: 10
    Last Post: 03-27-2002, 02:50 PM
  5. GL Rotate problem
    By Eber Kain in forum Game Programming
    Replies: 1
    Last Post: 12-14-2001, 07:33 AM

Tags for this Thread