9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ビット演算 [4]:特定のビットを反転する

Posted at

排他的論理和(^)は、ビットの値が同じ場合は0、異なる場合は1を返す。
x ^ 1 = ~x, x ^ 0 = x なので、見方を変えると、0ならば反転、0ならば元の値のままとなる。
従って、特定のビットを反転したい場合は、そのビットを立てたマスクと排他的論理和(^)演算を行うといいぞ。

例えば、変数xの下位4ビットを反転したい場合は、以下の様に記述する。

x ^= 0x0f;

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?