Algorithm for copying N bits at arbitrary position from one int to another

前端 未结 7 1773
别那么骄傲
别那么骄傲 2021-01-31 21:36

An interesting problem I\'ve been pondering the past few days is how to copy one integer\'s bits into another integer at a given position in the destination integer. So, for exa

7条回答
  •  野的像风
    2021-01-31 21:59

    uint32_t copy_bits(uint32_t dst, uint32_t src, uint8_t end_bit, uint8_t start_bit)

    {

    uint32_t left, right, mask, result;
    
    if (end_bit <= start_bit)
    {
        printf("%s: end_bit:%d shall be greater than start_bit: %d\n", __FUNCTION__, end_bit, start_bit);
        return 0;
    }
    
    left   = ~0; // All Fs
    right  = ~0;
    result = 0;
    left  >>= ((sizeof(uint32_t)*8) - end_bit); // Create left half of mask
    right <<= start_bit; // Create right half of mask
    mask   =  (left & right); // Now you have the mask for specific bits
    result = (dst & (~mask)) | (src & (mask));
    printf("%s, dst: 0x%08x, src: 0x%08x, end_bit: %d, start_bit: %d, mask: 0x%08x, result: 0x%08x\n",
          __FUNCTION__, dst, src, end_bit, start_bit, mask, result);
    
    return result;
    

    }

提交回复
热议问题