Index
|
Expression
|
Purpose
|
Remarks
|
1
|
X & 1
|
Check whether number
is odd or even
|
All numbers are interms of 0’s and 1’s and hence it is sufficient check
the last bit
|
2
|
X << 1
|
Multiply by 2
|
|
3
|
X >> 1
|
Divide by 2( Integer Division
|
|
4
|
~X+1
|
Negative the number
|
Negative numbers are represented by two complement. (one’s complement
+1)
|
5
|
X ^ all’ones
|
Bit toggling (equivalent
to ~)
|
|
6
|
X >> 31
|
To find out the sign of number X.
|
Result is 0 or 1 based on the sign.
|
7
|
Mask =
(X-Y) >> 31
Result = (Mask & X) | (~Mask & Y)
|
Min(X, Y) without using
comparisons
|
Mask contains all zeros if Y is less than or equal to X and all ones if
X is less than Y.
|
8
|
Mask =
(X-Y) >> 31
Result = (Mask & Y) | (~Mask & X)
|
Max(X, Y) without using comparisons
|
Mask contains all zeros if X is greater than or equal to Y and all ones
if Y is greater than X.
|
Tricks,Tips, Tweaks of Embedded C, C, Micro-controllers, Peripherals, Compilers, Datasheets, Linux, RTOS and Embedded Communication Protocols.
Pages1
C programming :Handy Bitwise Expressions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment