Saturday, September 17, 2011

A to Z of C - An advanced C programming for expert c programmers

This is a interested article that provides many deep c programming skills and related topics. If you want to understand c and computer architecture more deep, it is good article.


XOR operator manipulation 
Consider that the meaning of xor operator ^ in C programming language. 
It is a bit-wise operator in c programming language and its manipulation as below. 
1^1 = 0 ; 1^0 = 1 ; 0^1 = 1 ; 0^0 = 0 ; that means the result is 1 if two bits are different ; otherwise it is 0.
okay. Now we use it to design an easy macro that can exchange two numbers.
#define swap(x,y) (x^=y=x^=y)
We can try to break the above expression into more clear sub expressions as below.  
For example , x = 1 ; y = 0 ;
x^=y ;   // equivalent to x = x^y ; x= 1^0 = 1 ;
y=x^y = 1 ;
x^=y ;   //  x = x^y = x^1 = 1^1 = 0 ;   
We can obverse a characteristics ; that is xor operator can be as a switch.
Consider that the following expression .
n^=(1^2) means n = n^(1^2) , for example ,
n =1 , n = 1^(1^2) = 1^3 = 2
n =2 , n = 2^(1^2) = 2^3 = 1
...... However , we can obverse this is a recursive cycle , such like a toggling switch.
We can design a macro that can toggles any two values as below.
#define Toggle(n,x,y) \
for  ( int i = 0 ; i  < n ; i ++ , n^=(x^y) ) \
 cout << n << endl ; 

Crypt and Decrypt  
We may utilize xor operator to crypt and decrypt. The reason is it owns a special property - toggle behavior. 













 

No comments:

Post a Comment