7

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?

Community
  • 1
  • 1
Connor Black
  • 6,921
  • 12
  • 39
  • 70
  • 2
    The second one is wrong - the first and third are OK. Think about it - flipping (inverting) a bit twice does not unset it. – Paul R Aug 09 '12 at 13:34
  • 3
    ... and as this question shows, please do some search before asking a question. The duplicate that Paul points to is just one possible resource on the web for this question. – Jens Gustedt Aug 09 '12 at 14:24

4 Answers4

6

Set uses or

Unset uses And

Flip uses Xor

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

Community
  • 1
  • 1
Gir
  • 839
  • 5
  • 11
2

You are right for the first one, but for Unset() you should use an & with 0 in that bit

Dan F
  • 17,654
  • 5
  • 72
  • 110
0
    00000000 |
    00000001 =
--------------
    00000001   // Sets

    00000001 &
    00000000 =
--------------
    00000000   // Unsets

    00000001 ^
    00000001 =
--------------
    00000000   // Flips

If bit is which bit is to be manipulated in the byte:

x |= (1 << bit);    // Sets
x &= ~(1 << bit);   // Unsets   00000001 becomes 11111110.
x ^= (1 << bit);    // Flips
Chris Dargis
  • 5,891
  • 4
  • 39
  • 63
0

for the nth bit in a number x...

int Set(x, n){
   return x | (1 << n);
}

int Unset(x, n){
   return (x ^ (1 << n)) ^ (1 << n);
}

int Flip(x, n){
   return x ^ (1 << n);
}
Jawwad Zakaria
  • 1,139
  • 3
  • 13
  • 27