You can exchange values in C language without the need of the temporary storage location using three bitwise Exclusive-OR operator, look at code below:
#include <stdio.h>
int main(int argc, char *argv[])
{
int A;
int B;
A = 16;
B = 30;
printf("A=%d B=%d\n",A,B);
A ^= B;
B ^= A;
A ^= B;
printf("A=%d B=%d\n",A,B);
return 0;
}
The code after compiled will exchange value of variabel A with B, where A = 16 and B = 30 become A = 30 and B = 16.
How it works?
Value of A is XOR-ed with B value, the result then stored in A, then B XOR-ed with the altered A , this will produce the original value of A, this value then stored in B. Last, altered A value is XOR-ed with the altered B, this will produce the original B.
Here the schematically detail of its process:
A = 16 (decimal) --> 10 (hexadecimal) --> 0001 0000 (binary)
B = 30 (decimal) --> 1E (hexadecimal) --> 0001 1110 (binary)
on A ^= B statement, A being XOR-ed with B:
0001 0000 --> A
0001 1110 --> B
---------- XOR
0000 1110 --> A
the result 0000 1110 then stored in A,
on B ^= A statement, B being XOR-ed with A:
0001 1110 --> B
0000 1110 --> A
---------- XOR
0001 0000 --> B
the result 0001 0000 (16 decimal) stored in B,
on A ^= B statement, B XOR-ed with A:
0000 1110 --> A
0001 0000 --> B
---------- XOR
0001 1110 --> A
the result 0001 1110 (30 decimal) stored in A.
So the final result is:
A = 30 dan B = 16.
Have a nice try :).
Blog Archive
-
▼
2009
(13)
-
▼
April
(9)
- Exchanging two variables value without using tempo...
- Simple File Encryption
- Simple GUI with MATLAB® pragmatically programming
- A Child Called "It", a review
- Rosetta Stone V3.2 On Linux with Wine
- What is a Virtual Machine on Linux (Virtualization...
- Comix, software makes comic reading easier
- Running Mavis Beacon Teaches Typing Deluxe 17 on Wine
- Playing Nintendo64 games in PC
-
▼
April
(9)
Wednesday, 29 April 2009
Subscribe to:
Post Comments (Atom)
Category
- books (1)
- Game (1)
- news (1)
- Programming (3)
- Software (5)
- System (1)
- Terminology (1)
No comments:
Post a Comment