For loop prints all the numbers of a range instead of the bitwise condition values

Viewed 43

I am trying to make a small program where the user inputs numbers between 0 and 31 without limit, and when the input is -1, all the previous values must be printed without repetition. I am trying to use bitwise operators, but all the values between the range are being printed instead of the input values. What should I do?

This is my code:

int main()
{
    int x = 0, buffer, z;
    
    while (x != -1) {
        printf("User input: \n");
        scanf("%d", &x);
        buffer = x;
    }

    for (z = 0; z <= 31;z++) {
        if ((buffer & z) == z) {
            printf("%d\n", z);
        }
    }
    
    return 0;
}

I appreciate any help.

1 Answers

When value N is in the input, set bit N in the bitfield of buffer. That prevents repetition, and takes advantage of the input being limited 0-31.
The bits that can be set are also bits 0-31.

I used uint32_t from stdint.h to be more explicit about a 32-bit wide, unsigned field.

#include <stdio.h>
#include <stdint.h>
 
int main()
{
    int x = 0;
    uint32_t buffer = 0;
 
    do
    {
        printf("User input: \n");
        scanf("%d", &x);
        buffer |= ((x!=-1)<<x);
        // Set a single bit in the bit-field.  NOTE: No error check for invalid values.
    } while (x != -1);
 
    printf("Output:\n");
    for (int i = 0; i < 32; i++) {
        if (buffer & (1<<i)) {
            printf("%d ", i);
        }
    }
 
    return 0;
}

Input:

16 0 20 2 31 26 -1

Output

Output:
0 2 16 20 26 31 
Related