Thread: Bit rotation...

  1. #1
    Registered User
    Join Date
    Nov 2004
    Location
    Pennsylvania
    Posts
    434

    Bit rotation...

    How do you rotate bits in C++?

    I think i know a bitshift ( >> ) right? But that clips off the edges dont it?


    Any help would be appreciated! Thanks!
    "Anyone can aspire to greatness if they try hard enough."
    - Me

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Catch the bits which would fall off the end, then add them back in yourself.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered Usurer
    Join Date
    Apr 2005
    Location
    upstate NY
    Posts
    79
    They have to be rotated every 5,000 miles or they will wear prematurely. Also be sure to keep your bits properly inflated for better fuel efficiency.
    Huh?

  4. #4
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by Junior89 View Post
    How do you rotate bits in C++?

    I think i know a bitshift ( >> ) right? But that clips off the edges dont it?


    Any help would be appreciated! Thanks!
    Assuming chars are octets:

    Code:
    unsigned char rotate_left(unsigned char v, int n)
    {
        return (v << n) | (v >> (8 - n) );
    }
    Same basic idea for other size types. Always use unsigned types for this.

  5. #5
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    Quote Originally Posted by brewbuck View Post
    Assuming chars are octets:

    Code:
    unsigned char rotate_left(unsigned char v, int n)
    {
        return (v << n) | (v >> (8 - n) );
    }
    Same basic idea for other size types. Always use unsigned types for this.
    Easily generalized for all char implementations with
    Code:
     return (v << n) | (v >> (std::numeric_limits<char>::digits - n) );
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bit value check efficiency
    By George2 in forum C Programming
    Replies: 5
    Last Post: 11-05-2007, 07:59 AM
  2. Porting from 32 bit machine to 64 bit machine!
    By anoopks in forum C Programming
    Replies: 10
    Last Post: 02-25-2005, 08:02 PM
  3. Bit Manipulation Questions
    By CPPNewbie in forum C++ Programming
    Replies: 7
    Last Post: 08-12-2003, 02:17 PM
  4. Problem multiplying rotation matrices together
    By Silvercord in forum A Brief History of Cprogramming.com
    Replies: 20
    Last Post: 03-04-2003, 09:20 AM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM