On the run!

Loneliness
posts - 15, comments - 0, trackbacks - 0, articles - 5

JAVA 移位运算符 << >> >>>

Posted on 2008-03-28 10:08 痛哭的小强 阅读(174) 评论(0)  编辑  收藏

/*
* show the arthimetic character of '<<' '>>' '>>>'
*/

public class TestArithmetic {
   public TestArithmetic() {
   }
  
   public   static void   main(String [] args){
     int minus = -10;
     System.out.println(" Binary of -10 is " + Integer.toBinaryString(minus));
     System.out.println(" Arthimetic minus by -10 << 2 = " + (minus<<2) + " Binary is " + Integer.toBinaryString(minus<<2));
     System.out.println(" Arthimetic minus by -10 >> 2 = " + (minus>>2) + " Binary is " + Integer.toBinaryString(minus>>2));
     System.out.println(" Arthimetic minus by -10 >>>2 =   " + (minus >>> 2) + " Binary is " + Integer.toBinaryString(minus>>>2)
                        + ",length is " + Integer.toBinaryString(minus>>>2).length());
    
     int plus = 10;
     System.out.println(" Binary of 10 is " + Integer.toBinaryString(plus));
     System.out.println(" Arthimetic minus by 10 << 2 = " + (plus<<2)+ "Binary is " + Integer.toBinaryString(plus<<2));
     System.out.println(" Arthimetic minus by 10 >> 2 = " + (plus>>2)+ "Binary is "+ Integer.toBinaryString(plus>>2));
     System.out.println(" Arthimetic minus by 10 >>>2 =   " + (plus >>> 2)+ "Binary is "+ Integer.toBinaryString(plus >>> 2));
   }

补充知识:数值的补码表示也分两种情况:
(1)正数的补码:与原码相同。
例如,+9的补码是00001001。
(2)负数的补码:符号位为1,其余位为该数绝对值的原码按位取反;然后整个数加1。
例如,-7的补码:因为是负数,则符号位为“1”,整个为10000111;其余7位为-7的绝对值+7的原码0000111按位取反为1111000;再加1,所以-7的补码是11111001。


已知一个数的补码,求原码的操作分两种情况:
(1)如果补码的符号位为“0”,表示是一个正数,所以补码就是该数的原码。
(2)如果补码的符号位为“1”,表示是一个负数,求原码的操作可以是:符号位为1,其余各位取反,然后再整个数加1。
例如,已知一个补码为11111001,则原码是10000111(-7):因为符号位为“1”,表示是一个负数,所以该位不变,仍为“1”;其余7位1111001取反后为0000110;再加1,所以是10000111。



 


只有注册用户登录后才能发表评论。


网站导航: