简体   繁体   English

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

[英]Replicating the function of a for loop using only bitwise operators

I'm trying to replicate the function of a loop using only bitwise and certain operators including ! 我试图仅使用按位和某些运算符(包括!来复制循环的功能! ~ & ^ | ~ & ^ | + << >> + << >>

int loop(int x) {
   for (int i = 1; i < 32; i += 2)
     if ((x & (1 << i)) == 0)
       return 0;
   return 1; 
}

Im unsure however how to replicate the accumulating nature of a loop using just these operators. 但是我不确定如何仅使用这些运算符来复制循环的累加性质。 I understand shifting << >> will allow me to multiply and divide. 我知道转移<< >>将使我可以乘除。 However manipulation using ! 但是使用操纵! ~ & ^ ~ has proven more difficult. ~ & ^ ~已经证明比较困难。 Any Tips? 有小费吗?

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

Edit: I understand how the addition of bits can be achieved, however not how such an output can be achieved without first calling a while or for loop. 编辑:我知道如何实现位的加法,但是如果不先调用while或for循环就不能实现这种输出。

Maybe this can help: 也许这可以帮助:

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;
}

Your code tests all odd bits and returns 1 if all of them are set. 您的代码将测试所有奇数位,如果所有奇数位都已设置,则返回1。 You can use this bitmask: ...0101 0101 0101 Which, for 32 bits is 0xAAAAAAAA. 您可以使用以下位掩码:... 0101 0101 0101对于32位,为0xAAAAAAAA。 Then you take your value und bitwise-and it. 然后,您将您的价值和按位取舍。 If the result is the same as your mask, it means all bits are set. 如果结果与掩码相同,则意味着所有位均已设置。

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

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

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