C 언어: 비트 연산(bitwise operation)_000025

C언어: xor 연산(swap)


/// 연산

x = x ^ y
y = y ^ x
x = x ^ y

/// 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
// core gate --------------------------------------------------------------------
extern inline int not_gate(int x)          { return (~x);  }       // not gate
extern inline int or_gate(int x, int y)    { return (x | y); }     // or gate
extern inline int and_gate(int x, int y)   { return (x & y); }     // and gate
extern inline int xor_gate(int x, int y)   { return (x ^ y); }     // xor gate
extern inline int l_shift(int x, int bits) { return (x << bits); } // left shift 
extern inline int r_shift(int x, int bits) { return (x >> bits); } // right shift
//-------------------------------------------------------------------------------
 
//----------------------
// main() implementation 
int main(void) {
    int x, y;
     
    srand(time(NULL));
     
    x = r_shift(rand(), 24);
    y = r_shift(rand(), 24);    
 
    puts("x = x ^ y;");
    puts("y = y ^ x;");
    puts("x = x ^ y;");    
 
    puts("------ swap ------");    
    printf("            x = %4d, y = %4d\n", x, y);
    x = xor_gate(x, y);
    printf("1st round : x = %4d, y = %4d\n", x, y);
    y = xor_gate(y, x);
    printf("2nd round : x = %4d, y = %4d\n", x, y);
    x = xor_gate(x, y);
    printf("3rd round : x = %4d, y = %4d\n", x, y);    
 
    return 0
}
cs

* 실행환경: Linux(5.7.6-x86_64-linode136)
* 컴파일러: gcc (Ubuntu 6.5.0-2ubuntu1~14.04.1) 6.5.0 20181026


- 당신을 응원합니다. -

댓글

이 블로그의 인기 게시물

파이썬[Python]: 내장함수 - from_bytes 메서드

파이썬[Python]: 내장함수 - __len__ 메서드

파이썬[Python]: kivy - 한글 사용

C 언어: sin 함수, cos 함수, tan 함수

파이썬[Python]: 내장함수 - bit_length 메서드