最近在看java源碼的時候發現,int型在序列化操作的時候,做了如下操作:
//java.io.DataOutputStream#writeInt
/**
* Writes an <code>int</code> to the underlying output stream as four
* bytes, high byte first. If no exception is thrown, the counter
* <code>written</code> is incremented by <code>4</code>.
*
* @param v an <code>int</code> to be written.
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public final void writeInt(int v) throws IOException {
out.write((v >>> 24) & 0xFF);
out.write((v >>> 16) & 0xFF);
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(4);
}
平時見多了>>,倒是很少見>>>,這個是什麼操作呢?
1.Java >>>運算符 和 >> 運算符
>>> 在java 表示有符号右移。什麼意思呢?就是最高位符号位也會移動。
我們知道,>>表示有符号右移。
-1>> 1 = -1
-1>>2 = -1 還等于-1 右移多少位都是-1
>>>
-1 >>>1 = 2147483647
-1>>>2 = 1073741823
總結:
>>> 表示符号位也會跟着移動,比如 -1 的最高位是1,表示是個負數,然後右移之後,最高位就是0表示目前是個正數。
是以 -1 >>>1 = 2147483647
>> 表示無符号右移,也就是符号位不變。那麼-1 無論移動多少次都是-1
————————
原文連結:https://www.cnblogs.com/caoxinyu/p/10568485.html
驗證一下:
public class Demo05 {
public static void main(String[] args) {
//1.在計算機中,負數是以對應補碼形式存放的
//2.在Java中int占用四個位元組
//3.-1對應的補碼形式:1111111 1111111 1111111 1111111
int v=-1;
// (v >>> 24) & 0xFF;
System.out.println((v >>> 24));//0000000 0000000 0000000 1111111 255
// (v >>> 16) & 0xFF;
System.out.println((v >>> 16));//0000000 0000000 1111111 1111111 65535
// (v >>> 8) & 0xFF;
System.out.println((v >>> 8));// 0000000 1111111 1111111 1111111 16777215
// (v >>> 0) & 0xFF;
System.out.println((v >>> 0));// 1111111 1111111 1111111 1111111 -1
}
}
2.關于整數左移和右移擴大或縮小倍數問題
觀察如下數字的右移
十進制 二進制 右移後 對應十進制
2 0010 0001 1
3 0011 0001 1
4 0100 0010 2
6 0110 0011 3
8 1000 0100 4
9 1001 0100 3
可以這樣來看,由于是二進制,相鄰的兩個數之間相差的權值為2,左移一位就相當于擴大2倍,右移一位相當于縮小2倍。這樣左移n位或右移n位,擴大或縮小為原來的2^n倍(n>=1)。
參考連結:https://www.cnblogs.com/hongten/p/hongten_java_yiweiyunsuangfu.html