Posted on 2008-03-28 10:08
oathleo 閱讀(599)
評論(0) 編輯 收藏 所屬分類:
Java
/*
* 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。