Thread: bit operations

  1. #1
    Registered User
    Join Date
    Oct 2005
    Location
    Hyderabad, India
    Posts
    33

    bit operations

    I want to rotate right a number by n bits. I don't have the width of the word of the machine and i wan't to solve my problem without finding out the width.(one can always find out the width of a word by counting the number of 1 bits in ~0). Ne ideas ?

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You can't rotate a number in C without knowing the width. You can shift, but not rotate.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Since ~0 is all bits set, shifting it right by one and adding one will be the high bit. So you could start with something like this.
    Code:
    #include <stdio.h>
    
    unsigned int rotate(unsigned int value)
    {
       unsigned int lsb = value & 1;
       value >>= 1;
       if ( lsb )
       {
          value |= (~0U >> 1) + 1;
       }
       return value;
    }
    
    int main()
    {
       unsigned int num = 0xFFFF;
       printf("rotate(0x%X) = 0x%X\n", num, rotate(num));
       return 0;
    }
    
    /* my output
    rotate(0xFFFF) = 0x80007FFF
    */
    If you can get the high bit, you could get the n highest bits with a little more work.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Registered User
    Join Date
    Oct 2005
    Location
    Hyderabad, India
    Posts
    33
    thanks a lot dave

    -gaurav

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 32 bit to 64 bit Ubuntu
    By Akkernight in forum Tech Board
    Replies: 15
    Last Post: 11-17-2008, 03:14 AM
  2. 64 bit testing
    By DrSnuggles in forum C++ Programming
    Replies: 7
    Last Post: 11-20-2007, 03:20 AM
  3. bit value check efficiency
    By George2 in forum C Programming
    Replies: 5
    Last Post: 11-05-2007, 07:59 AM
  4. Replies: 7
    Last Post: 12-10-2004, 08:18 AM
  5. Array of boolean
    By DMaxJ in forum C++ Programming
    Replies: 11
    Last Post: 10-25-2001, 11:45 PM