C Programming - XOR Bitwise Operation

后端 未结 6 1143
傲寒
傲寒 2020-12-07 06:01

What operation does the following ‘C’ statement perform?

star = star ^ 0b00100100;

(A) Toggles bits 2 and 5 of

6条回答
  •  -上瘾入骨i
    2020-12-07 06:46

    If you know how XOR works, and you know that ^ is XOR in C, then this should be pretty simple. You should know that XOR will flip bits where 1 is set, bits 2 and 5 of 0b00100100 are set, therefore it will flip those bits.

    From an "during the test" standpoint, let's say you need to prove this to yourself, you really don't need to know the initial value of star to answer the question, If you know how ^ works then just throw anything in there:

     00100100
    ^10101010  (star's made up value)
    ---------
     10001110  (star's new value)
    
     bit position: | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0  
                   |---|---|---|---|---|---|---|---
     star's new v: | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0
                   |---|---|---|---|---|---|---|---
     star's old v: | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0
    

    Then check your answers again, did it:

    (A) Toggles bits 2 and 5 of the variable star. (Yes)

    (B) Clears all bits except bits 2 and 5 of the variable star. (Nope)

    (C) Sets all bits except bits 2 and 5 of the variable star. (Nope)

    (D) Multiplies value in the variable star with 0b00100100. (36x170 = 142? Nope)

提交回复
热议问题