Sobes.tech
Junior

How to obtain a number that can be represented in binary form with a single one?

sobes.tech AI

Answer from AI

This is a number that is a power of two. The most efficient way in C/C++ to obtain such a number with a one in the bit position n (zero-based indexing) is to use the bitwise shift operation.

// Get a number with a single one in the n-th bit
unsigned int get_power_of_two(int n) {
    if (n < 0) {
        // Error handling or return 0/throw exception depending on requirements
        return 0;
    }
    // 1U - unsigned int literal to avoid overflow during shift
    return 1U << n;
}

// Example usage
int main() {
    unsigned int num_at_bit_5 = get_power_of_two(5); // Will get the number 32 (00100000b)
    unsigned int num_at_bit_0 = get_power_of_two(0); // Will get the number 1 (00000001b)
    return 0;
}