好​​吧,你可以使用位操作和位逻辑。 unsigned char SomeValue = 27; bool MyBool1 = true ; bool MyBool2 = false; 首先,你想把0到63的值放在高位。这只是 意味着将位向左移两次。 unsigned char MyField = SomeValue<< 2; 现在,你想把第一个bool放在第二个LSB中。 MyField = MyField | (MyBool1?2:0); 现在你想把第二个bool放在最LSB中。 MyField = MyField | (MyBool2?1:0); 而不是MyBool1的常量2,你可以使用1<< 1更多自我 文档。 此时我相信MyField将包含您想要的内容。现在得出 的值: SomeValue =(Myfield>> 2)& 63; 我和它的原因是63(这是比特值111111)是因为我不是 确定符号位是否会被携带。如果它确实或不是& 没有伤害。 现在为MyBool1: MyBool1 = MyField& 2; 任何非零值都是真的。如果第二个LSB设置为MyBool1设置为 为true,否则它是假的。 MyBool2:同样简单。 MyBool2 = MyField& 1; 这是一点点操纵。看看运营商:& (按位和)| (按位或)<< (向左移动)和>> (右移)。 Well, you can use bit manipulation and bit logic. unsigned char SomeValue = 27;bool MyBool1 = true;bool MyBool2 = false; First, you want to put the 0 to 63 value in the high bits. This simplymeans to shift the bits to the left twice. unsigned char MyField = SomeValue << 2;Now, you want to put the first bool in the 2nd LSB.MyField = MyField | ( MyBool1 ? 2 : 0 );Now you want to put the second bool in the most LSB.MyField = MyField | ( MyBool2 ? 1 : 0 ); Instead of the constant 2 for MyBool1 you could use 1 << 1 for more selfdocumentation. At this point I believe that MyField will contain what you want. Now to getthe values out: SomeValue = ( Myfield >> 2 ) & 63;The reason I and it with 63 (which is bit value 111111) is because I''m notsure if the sign bit would be carried or not. If it does or doesn''t the &doesn''t hurt. Now for MyBool1:MyBool1 = MyField & 2;Any non zero value would be true. If the 2nd LSB is set MyBool1 is set totrue, otherwise it''s false.MyBool2: is just as easy.MyBool2 = MyField & 1; This is all bit manipulation. Look at the operators: & (bitwise and) |(bitwise or) << (shift left) and >> (shift right). 这篇关于操纵位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-18 22:47