개발하면서/etc

Swap방법

오산돌구 2009. 4. 25. 20:37
#define SWAP(a, b) ((&(a) == &(b)) || \
                    (((a) -= (b)), ((b) += (a)), ((a) = (b) - (a))))
#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))

임시 저장변수 없이 SWAP을 해준다.




unsigned int i, j; // positions of bit sequences to swap
unsigned int n;    // number of consecutive bits in each sequence
unsigned int b;    // bits to swap reside in b
unsigned int r;    // bit-swapped result goes here

int x = ((b >> i) ^ (b >> j)) & ((1 << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));

bit별 위치를 바꿀때 사용한다. i, j는 바꿀 처음 위치, n은 바꿀 크기이고, b는 원본, r은 바뀌어진 비트가 저장된다.

결론 : 영어공부를 열심히 하자 ;;;   출처 까먹었음;;