/** * Returns an {@code int} value with at most a single one-bit, in the * position of the highest-order ("leftmost") one-bit in the specified * {@code int} value. Returns zero if the specified value has no * one-bits in its two's complement binary representation, that is, if it * is equal to zero. * * @param i the value whose highest one bit is to be computed * @return an {@code int} value with a single one-bit, in the position * of the highest-order one-bit in the specified value, or zero if * the specified value is itself equal to zero. * @since 1.5 */ 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); }
读一下注释,可以理解,这个方法返回的是指定的某个数,从左到右开始(leftmost),第一个”1”后面的位数全部补0,返回其int结果。 举个栗子,这个函数的 i 传入 88888888,因为java 中 int 是32位的,她的值用二进制表示是:0000,0101,0100,1100,0101,0110,0011,1000,最左边的“1”右边全部清零,就变成了0000,0100,0000,0000,0000,0000,0000,0000,其int结果是2^26,等于67108864。
代码解读
函数只有简短五行代码(不算注释)。
把 i 右移一位,并与原数据按位取或,这样就使最高位1和她的下一位都变成了1;
把刚刚得到的两个1再右移两位,并与原数据按位取或,这样刚刚连续的两个1,就变成四个1了;
把刚刚的四个1右移四位,并与原数据按位取或,这样就得到八个连续的1了;
省略两步。结果是右移完16位后,最高位1和她右边的都是1;
最后 i 减去 i无符号右移1位的值,就得到结果。 因为最后一步是无符号右移,所以参数是负数得到的结果不是0,永远是0x80000000,也就是int的最小值
static int lowestOneBit(int i)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/** * Returns an {@code int} value with at most a single one-bit, in the * position of the lowest-order ("rightmost") one-bit in the specified * {@code int} value. Returns zero if the specified value has no * one-bits in its two's complement binary representation, that is, if it * is equal to zero. * * @param i the value whose lowest one bit is to be computed * @return an {@code int} value with a single one-bit, in the position * of the lowest-order one-bit in the specified value, or zero if * the specified value is itself equal to zero. * @since 1.5 */ public static int lowestOneBit(int i) { // HD, Section 2-1 return i & -i; }