20 bit operations programmers should know

  Peter        2012-12-19 12:53:33       28,082        6    

While talking about bit operation, programmers usually think about its efficiency. In embedded programming and system core optimization, appropriate use of bit operations is always a fascinating. When finding a job, it will help you a lot if you use bit operations when writing codes. Mastering simple bit arithmetic skills is necessary.

1. Get maximum int value

  1. int getMaxInt(){  
  2.         return (1 << 31) - 1;//2147483647,  

Another way:

  1. int getMaxInt(){  
  2.     return ~(1 << 31);//2147483647  

One more way:

  1. int getMaxInt(){
  2.     return (1 << -1) - 1;//2147483647  

In C, if you don't know how many bytes an int is.

  1. int getMaxInt(){  
  2.     return ((unsigned int) - 1) >> 1;//2147483647  

2. Get minimum int value

  1. int getMinInt(){  
  2.     return 1 << 31;//-2147483648  
  3.  } 

Another way

  1. int getMinInt(){
  2.     return 1 << -1;//-2147483648  

3. Get maximum long value

C version:

  1. long getMaxLong(){  
  2.     return ((unsigned long) - 1) >> 1;//2147483647  
  3. }

Java version :

  1. long getMaxLong(){  
  2.     return ((long)1 << 127) - 1;//9223372036854775807  

4. Multiply 2

  1. int mulTwo(int n){//计算n*2   
  2.     return n << 1;  

5. Divide by 2

  1. int divTwo(int n){
  2.     return n >> 1;//除以2  

6. Multiple 2m

  1. int mulTwoPower(int n,int m){
  2.     return n << m;  

7. Divide by 2m

  1. int divTwoPower(int n,int m){
  2.     return n >> m;  

8. Check whether a number is odd or even

  1. boolean isOddNumber(int n){  
  2.     return (n & 1) == 1;  

9. Exchange values of two variables

  1. void swap(int *a,int *b){     
  2.     (*a) ^= (*b) ^= (*a) ^= (*b);     

Common version

  1. a ^= b;  
  2. b ^= a;  
  3. a ^= b; 

10. Get absolute value

  1. int abs(int n){  
  2. return (n ^ (n >> 31)) - (n >> 31);

n>>31 will get the sign of n, if n is positive, then n>>31 is 0, if n is negative, n>>31 is -1. If n is positive, then n^0=n. If n is negative, then to calculate n^-1 , we need to calculate n and -1's complement and then do exclusive or operation. Then n will change the sign and the value is absolute value of n minus 1. So at last, do a minus -1 to get the absolute value.

11. Get bigger value of two values

  1. int max(int a,int b){  
  2.     return b & ((a-b) >> 31) | a & (~(a-b) >> 31);  

C version:

  1. int max(int x,int y){  
  2.     return x ^ ((x ^ y) & -(x < y));  

12. Get smaller value of two values

  1. int min(int a,int b){  
  2.     return a & ((a-b) >> 31) | b & (~(a-b) >> 31);  

C version:

  1. int min(int x,int y){  
  2.     return y ^ ((x ^ y) & -(x < y));  

13. Check whether two values have the same sign

  1. boolean isSameSign(int x, int y){
  2.     return (x ^ y) >= 0;

14. Calculate 2n

  1. int getFactorialofTwo(int n){//n > 0  
  2.     return 2 << (n-1);

15. Check whether a value can be divided by 2

  1. boolean isFactorialofTwo(int n){  
  2.     return n > 0 ? (n & (n - 1)) == 0 : false;  

16. Get remainder of 2n

  1. int quyu(int m,int n){
  2.     return m & (n - 1);

17. Get average value of two values

  1. int getAverage(int x, int y){  
  2.         return (x + y) >> 1;   
  3. } 

Another way:

  1. int getAverage(int x, int y){  
  2.         return ((x ^ y) >> 1) + (x & y);   
  3. }  

18. Get the mth bit of a number n

  1. int getBit(int n, int m){  
  2.     return (n >> (m-1)) & 1;  

19. Set the bit to 1 at mth bit of a number n

  1. int setBitToOne(int n, int m){  
  2.     return n | (1 << (m-1));  

20. Set the bit to 0 at mth bit of a number n

  1. int setBitToZero(int n, int m){  
  2.     return n & ~(1 << (m-1));

Here is one more article regarding using bit operation to realize addition, subtraction, multiplication and division. : Implementation of +,-,*,/ with bitwise operator

Source : http://blog.csdn.net/nash_/article/details/8262185

TIPS  BIT OPERATION 

       

  RELATED


  6 COMMENTS


Sean [Reply]@ 2013-06-08 09:14:30

Great article! Very useful. The link at the end is dead due to an additional "article/" in the URL. Probably a typo! I was able to get to the page by removing it. Just though I'd post and let you know.

Peter [Reply]@ 2013-06-08 10:10:41

Hi, Sean. Thank you. The dead link issue is fixed now.

Someone [Reply]@ 2013-06-08 12:10:24

Please don't assume int is 32 bits.

 

 

Nathan [Reply]@ 2013-06-08 13:52:49

Your Java version for getting the maximum long value is correct, but a bit overdone. First, literals of type long can be expressed using the "L" suffix, so "(long)1" is probably better expressed as "1L". Further, since a Long is 64 bits rather than 128 bits, "127" should be replaced by "63". (127 only works because, if the first operand of a shift operation has type long, the second operand is masked for the lower 6 bits after unary promotion. In other words, your "127" is silently being converted to "63", anyway.)

But, the simplest (and arguably correct) way is to use the compile-time contant Long.MAX_SIZE.

Thanks for the article, though. Fun stuff.

Jeff [Reply]@ 2013-09-19 22:37:29
Excellent article! We are linking to this great content on our website. Keep up the great writing.
Neil Harding [Reply]@ 2016-08-08 16:48:34

1) Can also use

  1. int getMaxInt(){  
  2.         return (-1 >> 1);//2147483647,   
  3. }  

I used to use a really fast alternative to h = sqrt(a*a + b*b)

h = a | b (if both values are positive, otherwise force them to + first)

this is within 10%-20% and very handy when you need an approximate distance in a game for example.



  RANDOM FUN

Unable to connect to the Internet

When the Windows prompt you that "Unable to connect to the Internet, would you like to search online for solutions?". What would be your next reaction? Tell me. I promise I will not tell anyone else.