Bit hack: Expanding bits

前端 未结 8 1520
名媛妹妹
名媛妹妹 2021-02-13 21:27

I am trying to convert a uint16_t input to a uint32_t bit mask. One bit in the input toggles two bits in the output bit mask. Here is an example conver

8条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 22:08

    My solution is meant to run on mainstream x86 PCs and be simple and generic. I did not write this to compete for the fastest and/or shortest implementation. It is just another way to solve the problem submitted by OP.

    #include 
    #include 
    #include 
    
    #define BITS_TO_EXPAND (4U)
    #define SIZE_MAX (256U)
    
    static bool expand_uint(unsigned int *toexpand,unsigned int *expanded);
    
    int main(void)
    {
        unsigned int in = 12;
        unsigned int out = 0;
        bool success;
        char buff[SIZE_MAX];
    
        success = expand_uint(&in,&out);
        if(false == success)
        {
            (void) puts("Error: expand_uint failed");
            return EXIT_FAILURE;
        }
        (void) snprintf(buff, (size_t) SIZE_MAX,"%u expanded is %u\n",in,out);
        (void) fputs(buff,stdout);
        return EXIT_SUCCESS;
    }
    /*
    ** It expands an unsigned int so that every bit in a nibble is copied twice
    ** in the resultant number. It returns true on success, false otherwise.
    */
    static bool expand_uint(unsigned int *toexpand,unsigned int *expanded)
    {
        unsigned int i;
        unsigned int shifts = 0;
        unsigned int mask;
    
        if(NULL == toexpand || NULL == expanded)
        {
            return false;
        }
        *expanded = 0;
        for(i = 0; i < BIT_TO_EXPAND; i++)
        {
            mask = (*toexpand >> i) & 1;
            *expanded |= (mask << shifts);
            ++shifts;
            *expanded |= (mask << shifts);
            ++shifts;
        }
        return true;
    }
    

提交回复
热议问题