unsigned int a = 60; // 60 = 0011 1100 unsigned int b = 13; // 13 = 0000 1101 int c = 0; c = a & b ; // Result : 0000 1100 Bitwise AND. c = a | b ; // Result : 0011 1101 Bitwwise OR. c = a ^ b ; // Result : 0011 0001 Bitwise Exclusive-OR (XOR). c = ~a ; // Result : 1100 0011 Bitwise complement. c = a << 2 ; // Result : 1111 0000 Bitwise Left Shift. Right Shift 2, all bits are shifted to Right by two places. c = a >> 2 ; // Result : 0000 1111 Bitwise Right Shift. Left Shift 2, all bits are shifted to Left by two places. (Right Shift 1 is equivalent to multiply by 2)
a &= 2 ; is same as a = a & 2 a |= 2 ; is same as a = a | 2 a ^= 2 ; is same as a = a ^ 2 a <<= 2 ; is same as a = a << 2 a >>= 2 ; is same as a = a >> 2
XOR swap algorithm
Swap values of distinct variables having the same data type without using a temporary variable.
http://en.wikipedia.org/wiki/XOR_swap_algorithm
Function that implements the XOR swap algorithm :
void xorSwap (int *x, int *y)
{
if (x != y)
{
*x ^= *y ;
*y ^= *x ;
*x ^= *y;
}
}
if an attempt is made to XOR-swap the contents of some location with itself, the result is that the location is zeroed out
and its value lost.
.
The XOR swap algorithm can also be defined with a macro :
#define xorSWAP(a, b) ( (a)^=(b) , (b)^=(a), (a)^=(b) )
.
Replacing XOR by addition and subtraction gives a slightly different, but largely equivalent, formulation :
void addSwap (unsigned int *x, unsigned int *y)
{
if (x != y)
{
*x = *x + *y ;
*y = *x - *y ;
*x = *x - *y ;
}
}
Unlike the XOR swap, this variation requires that the underlying processor or programming language uses a method such
as modular arithmetic or bignums to guarantee that the computation of X + Y
cannot cause an error due to integer overflow.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.