简体   繁体   English

设置二进制数等于设置掩码的其他二进制数

[英]Set binary number equal to other binary number where mask is set

I have the following three values:我有以下三个值:

PORTB  = 00011011
Mask   = 00000111
Value  = 00100110

With these values I am trying to set PORTB equal to Value where the Mask is set to one.使用这些值,我试图将 PORTB 设置为等于掩码设置为 1 的值。 The output would be the following: output 如下:

Output = 00011110

As you can see I am not messing with the first 5 bits of PORTB.如您所见,我并没有弄乱 PORTB 的前 5 位。 The last three bits though I am setting.最后三位虽然我正在设置。 Of course this wouldn't be the case if the Mask and Value were even more complex.当然,如果 Mask 和 Value 更复杂,情况就不会如此。 There doesn't seem to be an operator that can help me solve this equation, I did try the following:似乎没有一个运算符可以帮助我解决这个等式,我确实尝试了以下方法:

Mask    = 00000111
Value   = 00100110
------------------ AND
PORTB   = 00011011
Output1 = 00000110
------------------ ??? This is where I get stuck, my first step doesn't seem to help much...
Output2 = 00011110

I hope someone can help me out as I can't find any solution/answer online which can help me.我希望有人可以帮助我,因为我在网上找不到任何可以帮助我的解决方案/答案。

If i understood it correctly, this should be what you're looking for如果我理解正确,这应该是你要找的

PORTB = (PORTB & ~Mask) | (Value & Mask);

Here's what it does这是它的作用

PORTB   = 00011011
~Mask   = 11111000 
------------------ AND
Output1 = 00011000

Value   = 00100110 
Mask    = 00000111 
------------------ AND
Output2 = 00000110


Output1 = 00011000
Output2 = 00000110
------------------ OR
Output  = 00011110

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

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