Friday, June 16, 2006

Q & A Bitwise operations in C/C++

Q & A Bitwise operations in C/C++

Bitwise operations mean fast machine performance.
Using Macros means eliminating time cost of a function call.

Bitwise operations:


& Bitwise AND
| Bitwise OR
^ XOR
~ One's compliment flip bits
<<>> Right shift

Bitwise Q & A:


# define UNITY 0x00000001

Q: I want to raise a number to a power of x 2^x?
A:
#define TWOPWR( x ) UNITY << (x) int z = TWOPWR(x) ;

Q: I want to a get a bit of position pos from x?

A:
#define GETBIT(x,pos) ( ((x) & ( UNITY << (pos) ))!=0 ) unsigned x = 25 ; bool bit = GETBIT(x,5) ;

Q: I want to a set a bit of position pos from x by true?

A:
#define SETBIT(x,pos) ( (x) | ( UNITY << (pos) ) ) unsigned x = 25 ; x = SETBIT(x,10) ;

Q: I want to a reset a bit of position pos from x by false?

A:
#define RESETBIT(x,pos) ( (x) & ~( UNITY << (pos) ) ) unsigned x = 25 ; x = RESETBIT(x,0) ;

Q: I want to a reset a bit of position pos from x by false?

A:
#define ISPWRTWO(x) (!((x) & ((x) - 1))
bool bit = ISPWRTWO(5) ;

Q: I want to swap 2 variables a, b without external space?
A:
#define SWAP(x, y) (((x) ^= (y)), ((y) ^= (x)), ((x) ^= (y)))
int d = 8 , e = 9 ;
SWAP(d,e) ;

Q: In my assembler I want to set n, i, x, ….?
A: Just use SETBIT Macro and use bit 6
#define NPOSITION 6
#define SETBIT(x,pos) ( (x) | ( UNITY << (pos) ) ) unsigned x = 25 ; x = SETBIT(x, NPOSITION); Other faster idea is to compute UNITY << style="color: rgb(51, 51, 255); font-weight: bold;">Q: I want to multiply an integer by 640?
A: Never use multiplications for multiplying an integer with a constant value. instead use addition and shift operations.
#define MUL640(x) ( ((x)<<7) + ((x)<<9) )
int x = MUL640(3) ;
We used 3 operations to multiply x by 640. But they are faster than operator *.
x = x *(128 + 512) ;
x = x * 128 + x * 512 ;

No comments: