Web Toolbar by Wibiya

Pages

Monday, January 30, 2012

Implement mask_and_set_bits()

Solution #1: Given an integer 'value', a position 'pos', an integer 'n' and another integer 'bits'. Replace 'n' bits in 'value' starting at position 'pos' with 'bits'. Here is the code written for 32-bit architectures,

void mask_and_set_bits(unsigned int* val, unsigned int pos, unsigned int n, unsigned int bits)
{
    *val = (*val)&((0xFFFFFFFF << (pos+n))| ~(0xFFFFFFFF << pos));
    *val = *val|(bits << pos)&~((0xFFFFFFFF << (pos+n))|~(0xFFFFFFFF << pos));
}

No comments: