优秀程序员不得不知道的20个位运算技巧 【转】
2013-02-23 19:32
525 查看
【转载】一提起位运算,人们往往想到它的高效性,无论是嵌入式编程还是优化系统的核心代码,适当的运用位运算总是一种迷人的手段,或者当您求职的时候,在代码中写入适当的位运算也会让您的程序增加一丝亮点,最初当我读《编程之美》求“1的数目”时,我才开始觉得位运算是如此之美,后来读到 《Hacker's Delight》,感慨到Henry S.Warren把位运算运用的如此神出鬼没,很多程序都十分精妙,我觉得在一个普通的程序中大量运用这样的代码的人简直是疯了!但掌握简单的位运算技巧还是必要的,所以今天写这篇博文把我积累的一些位运算技巧分享给大家,这些技巧不会是如求“1的数目”的技巧,是最基本的一行位运算技巧 !
int getMaxInt(){
return (1<<31) - 1; //2147483647, 由于优先级关系,括号不可省略
}
int getMaxInt(){
return -(1<<-1) - 1; //2147483647
}
int getMaxInt(){
return ~(1<<31); //2147483647
}
int getMaxInt(){
return ((unsigned int )- 1 ) >> 1 ; //2147483647
}
int getMinInt(){
return 1<<31; //-2147483648
}
int getMinInt(){
return 1 << -1; //-2147483648
}
long getMaxLong(){
return ((unsigned long )-1) >> 1; //2147483647
}
long getMaxLong(){
return (( long ) 1 << 127 )- 1 ; //9223372036854775807
}
获得long最小值,和其他类型的最大值,最小值同理.
int mulTwo( int n){ //计算n*2
return n<<1;
}
int divTwo( int n){ //负奇数的运算不可用
return n>>1; //除以2
}
int mulTwoPower( int n, int m){ //计算n*(2^m)
return n<<m;
}
int divTwoPower( int n, int m){ //计算n/(2^m)
return n>>m;
}
1.获得int型最大值
[cpp] view plain copyint getMaxInt(){
return (1<<31) - 1; //2147483647, 由于优先级关系,括号不可省略
}
另一种写法
[cpp] view plain copyint getMaxInt(){
return -(1<<-1) - 1; //2147483647
}
另一种写法
[cpp] view plain copyint getMaxInt(){
return ~(1<<31); //2147483647
}
C语言中不知道int占几个字节时候
[java] view plain copyint getMaxInt(){
return ((unsigned int )- 1 ) >> 1 ; //2147483647
}
2.获得int型最小值
[cpp] view plain copyint getMinInt(){
return 1<<31; //-2147483648
}
另一种写法
[cpp] view plain copyint getMinInt(){
return 1 << -1; //-2147483648
}
3.获得long类型的最大值
C语言版
[cpp] view plain copylong getMaxLong(){
return ((unsigned long )-1) >> 1; //2147483647
}
JAVA版
[java] view plain copylong getMaxLong(){
return (( long ) 1 << 127 )- 1 ; //9223372036854775807
}
获得long最小值,和其他类型的最大值,最小值同理.
4.乘以2运算
[cpp] view plain copyint mulTwo( int n){ //计算n*2
return n<<1;
}
5.除以2运算
[cpp] view plain copyint divTwo( int n){ //负奇数的运算不可用
return n>>1; //除以2
}
6.乘以2的m次方
[cpp] view plain copyint mulTwoPower( int n, int m){ //计算n*(2^m)
return n<<m;
}
7.除以2的m次方
[cpp] view plain copyint divTwoPower( int n, int m){ //计算n/(2^m)
return n>>m;
}
相关文章推荐
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 【基础备忘】优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 转:优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧
- 优秀程序员不得不知道的20个位运算技巧