LoginSignup
3
3

More than 5 years have passed since last update.

ビット演算 [5]:2つの変数の特定のビットを交換する

Last updated at Posted at 2014-09-07

排他的論理和は x^x = 0, x^0 = x であり、交換法則も成り立つので、
x^(x^y) = y, y^(x^y) = x である。
従って、変数 x, y をそっくり交換したい場合は以下のように記述できる。

auto t = x ^ y;
x ^= t;
y ^= t;

特定のビットのみを交換したい場合は、t の計算時にその部分をマスクしてやるとよい。
例えば、変数 x, y の下位4bitの部分だけを交換したい場合は以下のように記述するといいぞ。

auto t = (x ^ y) & 0x0f;
x ^= t;
y ^= t;

x = 0x123, y = 0xabc の場合、上記を実行すると x = 0x12c, y = 0xab3 になるぞ。

3
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
3
3