We help IT Professionals succeed at work.

get full value

bachra04
bachra04 asked
on
Medium Priority
250 Views
Last Modified: 2010-04-15
I want a create a function                            
                                                     
unsigned int GetFullVal ( unsigned int InValue)    
{                                                    
    ...                                              
}                                                    
                                                     
that do the following:                                
                                                     
input val (binary )  |   output val (binary)          
1                    |   1                            
10                  |   11                          
100                |   111                          
1000              |   1111                        
10000            |   11111                        
...                                                  
                                                     
I want an elegant solution ?        

Thanks,

BT                  
Comment
Watch Question

Commented:
you want to fill in the bits given  2**n


unsigned int GetFullVal ( unsigned int a)    
{
        unsigned int answer = 0;
        unsinged int bit;

       if(a == (1 << 31))
             return ~0;

        for(bit = 1; bit  <= a; bit <<= 1) {
                answer |= bit;

        }
        return answer;

}

No check to confirm a is a power of 2.
Need the if at the start to process 2 ** 31. (assuming sizeof(int) == 4) probably replace
31 with ((sizeof(unsigned int) * 8) - 1.


Commented:
if (in == (1 << 31)) return ~0 ;
else return (in << 1) - 1 ;

it should work if in is a power of 2

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.