Java Integer中的highestOneBit()和lowestOneBit()方法
来源:互联网 发布:linux redis 启动 编辑:程序博客网 时间:2024/04/30 05:11
1.highestOneBit方法
传入一个int参数i,返回其二进制最高位1的权值。
- 若i为正整数,例如i=9,其二进制为1001,最高位1的权值为8,则返回值为8
- 若i为负整数,最高位1为符号位,返回值为-2147483648
- 若i为零,返回值为0
源码如下:
public static int highestOneBit(int i) { // HD, Figure 3-1 i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1);}
解析:
以129为例,二进制为10000001i: 1 0 0 0 0 0 0 1i >> 1: 0 1 0 0 0 0 0 0二者位或: 1 1 0 0 0 0 0 1同理,整个过程如下: 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 ...i - (i >>> 1): 1 1 1 1 1 1 1 1 - 0 1 1 1 1 1 1 1 = 1 0 0 0 0 0 0 0返回值为128
整个过程可以理解为最高1位向右复制,然后将最高2位向右复制,再将最高4位向右复制……
这样最多经过五次迭代就能得到最终的结果。
2.lowestOneBit方法
传入一个int参数i,返回其二进制最低位1的权值。
- 若i非零,返回值为最低位1的权值
- 若i为零,返回值为0
public static int lowestOneBit(int i) { // HD, Section 2-1 return i & -i;}
解析:
以12为例,二进制为1100i: 0 0 ... 0 1 1 0 0-i: 1 1 ... 1 0 1 0 0i & -i: 0 0 ... 0 0 1 0 0返回值为4
原理与负数的补码表示有关,由i按位取反再末位加1可以得到-i的补码。
也就是说,这个过程中最低位的1会变成0,其后的0全部变成1,加1后往前进位,
原位置又变回1,(i & -i)运算得到结果。
阅读全文
0 0
- Java Integer中的highestOneBit()和lowestOneBit()方法
- Java Integer.highestOneBit(i)代码
- Integer的highestOneBit方法源码解析
- Integer的highestOneBit方法源码解析
- Java Integer.highestOneBit(i)代码品读
- Java Integer.highestOneBit(i)代码品读
- Java Integer.highestOneBit(int num) 源码解析
- Java Integer.highestOneBit(i)代码品读
- Integer.highestOneBit、 Integer.bitCount 实现解析
- Java中的String和Integer
- Integer.highestOneBit(int i)的作用
- Integer中的valueOf方法和parseInt方法
- java中Integer中的hashCode方法
- java中的Integer的toBinaryString()方法
- Java中的int和Integer的区别
- java中的Integer和int比较
- 介绍一下java里的highestOneBit()
- 关于Java中的Integer
- 编程十戒
- 达内课程-流程控制语句(下)
- 委托和事件理解(转)
- 详解SVN的使用
- 博客园首页新随笔联系管理订阅 随笔- 216 文章- 1 评论- 2 Java ConcurrentModificationException异常原因和解决方法
- Java Integer中的highestOneBit()和lowestOneBit()方法
- 将list中的元素按照属性分类成树状的map
- React学习-- React源码(5)diff算法
- Android源码基础解析之系统启动并解析Manifest的流程
- 一个简单的定时任务
- CodeChef DEC14 RIN
- ios面试题全面
- loongson官方PMON使用
- Error:null value in entry: incrementalFolder=null