Java查找int中第一个为1的bit位置

public class BinarySearch {
	// find first bit which is 1 from left to right
	public static int search(int d) {
		int r = 0;
		if ((d & 0xffff0000) != 0) {
			d >>>= 16;
			r += 16;
		}
		if ((d & 0xff00) != 0) {
			d >>>= 8;
			r += 8;
		}
		if ((d & 0xf0) != 0) {
			d >>>= 4;
			r += 4;
		}
		if ((d & 0x0c) != 0) {
			d >>>= 2;
			r += 2;
		}
		if ((d & 0x02) != 0) {
			d >>>= 1;
			r += 1;
		}
		if ((d & 0x01) != 0) {
			r += 1;
		}
		return r;
	}

	// find first bit which is 1 from right to left
	public static int searchReserve(int d) {
		int r = 0;
		if ((d & 0xFFFF) == 0) {
			d >>= 16;
			r += 16;
		}
		if ((d & 0xFF) == 0) {
			d >>= 8;
			r += 8;
		}
		if ((d & 0x0F) == 0) {
			d >>= 4;
			r += 4;
		}
		if ((d & 0x03) == 0) {
			d >>= 2;
			r += 2;
		}
		if ((d & 0x01) == 0) {
			r += 1;
		}
		return r;
	}
}

  

posted on 2020-06-19 14:11  areful  阅读(963)  评论(0编辑  收藏  举报

导航