Search code examples
arrayscfor-loopbitwise-operatorsbit

Placing the bits of an int backwards in an array


Hi guys I'm a total beginner and this is my first post here. For a bigger project, I want every bit of the integer input to be placed backwards in an array that I have created. It works perfectly fine for the first row but every following row of the array is filled with 0s no matter the input. Any suggestions??

#include<stdio.h>


int main(int argc, char *argv[]){
    unsigned short int canvoted, mask;
    unsigned short int individualvote[3][7]={{0}};
    int i, j;
    
    mask=0b1;


    for(i=0; i<3; i++){
        printf("Give an int:\n");
        scanf("%hu", &canvoted);

        for(j=0; j<7; j++){
            individualvote[i][j] = canvoted & mask;
            individualvote[i][j] = individualvote[i][j] >> j;
            mask = mask << 1;
            printf("%hu ", individualvote[i][j]);
        }
        printf("\n##\n");
    }
    return(0);
}

Solution

  • Within the inner for loop you are changing the variable mask

    mask = mask << 1;
    

    and are not resetting it to its initial value in the outer for loop.

    Move this expression statement

    mask=0b1;
    

    inside the outer for loop.

    for(i=0; i<3; i++){
        mask=0b1;
        //...
    

    In fact the variable mask is redundant. You could write the inner for loop simpler without the variable and thus could avoid the bug. For example

        for(j=0; j<7; j++){
            individualvote[i][j] = canvoted & 1;
            canvoted >>= 1;
            printf("%hu ", individualvote[i][j]);
        }
    

    Or even like

        for(j=0; j<7 && canvoted != 0; j++){
            individualvote[i][j] = canvoted & 1;
            canvoted >>= 1;
            printf("%hu ", individualvote[i][j]);
        }