zoukankan      html  css  js  c++  java
  • Java >>>运算符 和 >> 运算符

    最近在看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

  • 相关阅读:
    A1023 Have Fun with Numbers (20分)(大整数四则运算)
    A1096 Consecutive Factors (20分)(质数分解)
    A1078 Hashing (25分)(哈希表、平方探测法)
    A1015 Reversible Primes (20分)(素数判断,进制转换)
    A1081 Rational Sum (20分)
    A1088 Rational Arithmetic (20分)
    A1049 Counting Ones (30分)
    A1008 Elevator (20分)
    A1059 Prime Factors (25分)
    A1155 Heap Paths (30分)
  • 原文地址:https://www.cnblogs.com/cosmos-wong/p/11862835.html
Copyright © 2011-2022 走看看