Link to home
Start Free TrialLog in
Avatar of bachra04
bachra04Flag for Canada

asked on

get full value

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                  
Avatar of leisner
leisner

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.


ASKER CERTIFIED SOLUTION
Avatar of zulti
zulti

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial