Thread: bit clearing problem

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    48

    bit clearing problem

    I'm using the following code to clear a bit in position pos (starting with position 0 on the far right) in the integer value. (Please don't comment on the stupidity of the code writing right now). When I give it an input of 15 and 1 it gives me some massively negative number (-2147483639) as the return value while it should be returning 13
    (clearing the first bit would effectively subtract two from the original value)
    Any ideas on why this is not working properly?
    Code:
    unsigned int IBCLR(int value, int pos)
    {
        unsigned int tempval = (unsigned)value;
        unsigned int temppos = (unsigned)pos;
    
        return tempval & (~((unsigned)1 << temppos));
    }

  2. #2
    *this
    Join Date
    Mar 2005
    Posts
    498
    I know you said not to clean it, but I rewrote it to make sure it was correct...

    I got 13 with this code:
    Code:
    #include <iostream>
    using namespace std;
    
    unsigned IBCLR (unsigned value, unsigned pos)
    {
        return value & (~(1U << pos));
    }
    
    int main () {
       cout << IBCLR (15, 1) << endl;
       cin.get();
    }
    Yes, your code works.
    Last edited by JoshR; 07-19-2005 at 05:31 PM.

  3. #3
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> it gives me some massively negative number
    And yet your return type is unsigned....how are you getting a negative number?

    Your code looks fine to me.

    gg

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Let's see his call to it. Possibly something like this?
    Code:
    unsigned int myfunction( ... );
    ...
    int x;
    ...
    x = myfunction( somestuff );

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bit level permutation function
    By zxcv in forum C Programming
    Replies: 2
    Last Post: 07-27-2008, 01:26 PM
  2. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  3. Copy bit to bit
    By Coder2Die4 in forum C Programming
    Replies: 15
    Last Post: 06-26-2003, 09:58 AM
  4. binary numbers
    By watshamacalit in forum C Programming
    Replies: 4
    Last Post: 01-14-2003, 11:06 PM
  5. Problem clearing screen
    By tim545666 in forum C++ Programming
    Replies: 9
    Last Post: 02-10-2002, 10:10 PM