Implement greater equal sign in C using only bitwise operations

后端 未结 3 801
生来不讨喜
生来不讨喜 2021-01-15 23:59

I know that many basic operations like addition or division can also be implemented in C using only bitwise operators. How can I do the same with the greater than or equal s

3条回答
  •  花落未央
    2021-01-16 00:39

    Simplest solution I can come up with:

    #include 
    
    if ((x & INT_MAX) == x)    // if (x >= 0)
        ...
    

    If you don't like the == then use XOR to do the equals test:

    #include 
    
    if ((x & INT_MAX) ^ x)    // if (x < 0)
        ...
    else                      // else x >= 0
        ...
    

提交回复
热议问题