简体   繁体   中英

C set 3 bits for a particular number

I am trying to understand masking concept and want to set bits 24,25,26 of a uint32_t number in C.

example i have

uint32_t data =0;

I am taking an input from user of uint_8 which can be only be value 3 and 4 (011,100)

I want to set the value 011 or 110 in bits 24,25,26 of the data variable without disturbing other bits.

Thanks.

To set bits 24, 25, and 26 of an integer without modifying the other bits, you can use this pattern:

data = (data & ~((uint32_t)7 << 24)) | ((uint32_t)(newBitValues & 7) << 24);

The first & operation clears those three bits. Then we use another & operation to ensure we have a number between 0 and 7. Then we shift it to the left by 24 bits and use | to put those bits into the final result.

I have some uint32_t casts just to ensure that this code works properly on systems where int has less than 32 bits, but you probably won't need those unless you are programming embedded systems.

More general approach macro and function. Both are the same efficient as optimizing compilers do a really good job. Macro sets n bits of the d at position s to nd . Function has the same parameters order.

#define MASK(n)   ((1ULL << n) - 1)
#define SMASK(n,s) (~(MASK(n) << s))
#define NEWDATA(d,n,s) (((d) & MASK(n)) << s)
#define SETBITS(d,nd,n,s) (((d) & SMASK(n,s)) | NEWDATA(nd,n,s))

uint32_t setBits(uint32_t data, uint32_t newBitValues, unsigned startbit, unsigned nbits)
{
    uint32_t mask = (1UL << nbits) - 1;
    uint32_t smask = ~(mask << startbit);
    data = (data & smask) | ((newBitValues & mask) << startbit);
    return data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM