get full value

Posted on 2006-03-25
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 ?        


Question by:bachra04
    LVL 3

    Expert Comment

    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.

    LVL 2

    Accepted Solution

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

    it should work if in is a power of 2


    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Join & Write a Comment

    Suggested Solutions

    Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
    This tutorial is posted by Aaron Wojnowski, administrator at  To view more iPhone tutorials, visit This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
    The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.
    Video by: Grant
    The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now