Home > Software design >  Placing the bits of an int backwards in an array
Placing the bits of an int backwards in an array

Time:12-08

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);
}

CodePudding user response:

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]);
    }

CodePudding user response:

  1. Use functions!!
  2. Your table is too short as byte has 8 not 7 bits!!!
  3. Always check the return value of the scanf function
unsigned short *fillBits(unsigned short *array, unsigned char val)
{
    unsigned short *wrk = array;
    memset(array, 0, sizeof(val) * CHAR_BIT);
    while(val)
    {
        *wrk   = val & 1;
        val >>= 1;
    }
    return array;
}

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


    for(i=0; i<3; i  )
    {
        printf("\nGive an int:\n");
        if(scanf("%hhu", &canvoted) != 1) {printf("Scanf error"); return 1;}
        fillBits(individualvote[i], canvoted);
    }
    printf("\n");
    for(i=0; i<3; i  )
    {
        for(size_t bit = 0; bit < CHAR_BIT; bit  )
           printf("%hd", individualvote[i][bit]);
        printf("\n");
    }

    return(0);
}

https://godbolt.org/z/98oYca4qz

for the data: 255, 128, 15

the output is

11111111
00000001
11110000
  • Related