8

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

Can some one help me how to toggle a bit at ith position. One way is to do ((n>>i) ^ 1) << i. Are there any other ways ?

Stoogy
  • 1,307
  • 3
  • 16
  • 34
brett
  • 5,379
  • 12
  • 43
  • 48
  • 1
    Duplicate of [How do you set, clear and toggle a single bit in C?](http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c) – James McNellis Sep 10 '10 at 01:13

2 Answers2

4

n ^= 1U << i is easy enough, isn't it?

Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
-1

You could do

pow(2, i) ^ n
Colin
  • 10,447
  • 11
  • 46
  • 54
  • 1
    you'd have to cast the (inexact) result of pow to an int for that to work. – Mark Elliot Sep 10 '10 at 01:15
  • 1
    No, you couldn't. `pow` returns a double, which is not a valid argument to the `^` operator. There's also no guarantee that `pow` will give an exact result. – Stephen Canon Sep 10 '10 at 01:16