简体   繁体   English

C 为特定数字设置 3 位

[英]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.我想了解掩码概念,并想在 C 中设置 uint32_t 数字的位 24,25,26。

example i have我有的例子

uint32_t data =0; uint32_t 数据 =0;

I am taking an input from user of uint_8 which can be only be value 3 and 4 (011,100)我正在接受 uint_8 用户的输入,它只能是值 3 和 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.我想在不干扰其他位的情况下在数据变量的位 24、25、26 中设置值 011 或 110。

Thanks.谢谢。

To set bits 24, 25, and 26 of an integer without modifying the other bits, you can use this pattern:要设置整数的第 24、25 和 26 位而不修改其他位,可以使用以下模式:

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 |然后我们使用另一个&操作来确保我们有一个介于 0 和 7 之间的数字。然后我们将它向左移动 24 位并使用| 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.我有一些uint32_t转换只是为了确保此代码在int少于 32 位的系统上正常工作,但除非您正在对嵌入式系统进行编程,否则您可能不需要这些。

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 .宏将位置s处的d n位设置为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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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