仅使用按位运算符复制for循环的功能

时间:2016-07-18 09:58:01

标签: c++ c for-loop bit-manipulation bitwise-operators

我试图仅使用按位和某些运算符复制循环函数,包括<xs:element name="NonTeachingActivity"> <xs:complexType> <xs:all> <xs:element name="NTCode" type="String10"/> <xs:element name="Description" type="String100"/> <xs:element name="Type" type="MeetingType"/> </xs:all> <xs:attribute name="RefId" type="GUID" use="required"/> </xs:complexType> </xs:element> ! ~ & ^ {{1} } | +

<<

我不确定如何仅使用这些运算符来复制循环的累积性质。我理解转移>> int loop(int x) { for (int i = 1; i < 32; i += 2) if ((x & (1 << i)) == 0) return 0; return 1; } 会让我倍增和分裂。但是,使用<< >> ! ~ &进行操纵已证明更为困难。任何提示?

http://www.tutorialspoint.com/cprogramming/c_operators.htm

编辑: 我理解如何实现位的添加,但是如果没有先调用while或for循环就不能实现这样的输出。

2 个答案:

答案 0 :(得分:4)

也许这会有所帮助:

int loop(int x) {
    x = x & 0xaaaaaaaa; // Set all even numbered bits in x to zero
    x = x ^ 0xaaaaaaaa; // If all odd numbered bits in x are 1, x becomes zero
    x = !x;             // The operation returns 1 if x is zero - otherwise 0
    return x;
}

答案 1 :(得分:0)

您的代码测试所有奇数位,如果所有位都设置,则返回1。您可以使用此位掩码:... 0101 0101 0101 其中,32位是0xAAAAAAAA。 然后你把你的价值和按位 - 和它。如果结果与掩码相同,则表示所有位都已设置。

int testOddBits(int x) {
    return (x & 0xAAAAAAAA) == 0xAAAAAAAA;
}