java编程思想练习题-第3章练习11,12-移位操作

题目:(1)以一个最高有效位为1的二进制数字开始,用有符号右移操作符对其进行右移,直至所有的二进制位都被移出为止。

 (2)亿一个所有位都是1的二进制数字开始,先左移它,然后用无符号右移操作对其右移,直至所有的二进制位被移出为止。

分析:java移位操作有有符号移位和无符号移位两种,这样来记,左移位<<低位补零,有符号右移位>>高位插符号位,无符号右移位>>>高位补零

import java.util.*; 
public class test {
	
	public static void main(String[] args) {
		int h = 0x10000000;
		System.out.println(Integer.toBinaryString(h));
		for(int i = 0; i < 28; i++) {
			h >>>= 1;
			System.out.println(Integer.toBinaryString(h));
		}
		System.out.println("-----------end1----------------------");
		
		h=0xffffffff;
		for(int i = 0; i < 3; i++) {
			h <<= 1;
			System.out.println(Integer.toBinaryString(h));
		}
		System.out.println("-------------end2--------------------");
		for(int i = 0; i < 28; i++) {
			h >>>= 1;
			System.out.println(Integer.toBinaryString(h));
		}
	}


}

结果:

10000000000000000000000000000
1000000000000000000000000000
100000000000000000000000000
10000000000000000000000000
1000000000000000000000000
100000000000000000000000
10000000000000000000000
1000000000000000000000
100000000000000000000
10000000000000000000
1000000000000000000
100000000000000000
10000000000000000
1000000000000000
100000000000000
10000000000000
1000000000000
100000000000
10000000000
1000000000
100000000
10000000
1000000
100000
10000
1000
100
10
1
-----------end1----------------------
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111000
-------------end2--------------------
1111111111111111111111111111100
111111111111111111111111111110
11111111111111111111111111111
1111111111111111111111111111
111111111111111111111111111
11111111111111111111111111
1111111111111111111111111
111111111111111111111111
11111111111111111111111
1111111111111111111111
111111111111111111111
11111111111111111111
1111111111111111111
111111111111111111
11111111111111111
1111111111111111
111111111111111
11111111111111
1111111111111
111111111111
11111111111
1111111111
111111111
11111111
1111111
111111
11111
1111

猜你喜欢

转载自buptchj.iteye.com/blog/2247460