Bitwise Manipulation Functions

Possible Duplicate:
How do you set, clear and toggle a single bit in C?

I'm studying for an upcoming final and I want to verify some questions from the study guide.

Some context:

  • The Set() function sets a bit in a byte to 1

  • The Unset() function sets a bit in a byte to 0

  • The Flip() function "flips" the bit to the opposite of what it is

  • So some kid in our class took it upon himself to answer the study guide questions but I've already found some errors, and these answers sound fishy. Here's what he said:

    Which operation is used for the Set? the or operator |

    Which operation is used for the Unset? Xor operator ^ Done twice

    Which operation is used for the Flip? Xor operator ^

    Are these the correct bitwise operators to implement in the functions I've described above?


    Set uses or

    Unset uses And

    Flip uses Xor

    this was already answered here: How do you set, clear, and toggle a single bit?


    你是对的第一个,但对于Unset()你应该使用&0在该位


        00000000 |
        00000001 =
    --------------
        00000001   // Sets
    
        00000001 &
        00000000 =
    --------------
        00000000   // Unsets
    
        00000001 ^
        00000001 =
    --------------
        00000000   // Flips
    

    如果bit是要在字节中处理的位:

    x |= (1 << bit);    // Sets
    x &= ~(1 << bit);   // Unsets   00000001 becomes 11111110.
    x ^= (1 << bit);    // Flips
    
    链接地址: http://www.djcxy.com/p/28796.html

    上一篇: 在一个字节中设置一个特定的位

    下一篇: 按位操作函数