high bits of long multiplication in Java?

前端 未结 7 993
说谎
说谎 2020-12-19 14:35

Is there any way to get the high half of the multiplication of two longs in Java? I.e. the part that vanishes due to overflow. (So the upper 64 bits of the 128-

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 15:20

    Let's say you have two longs, x and y, and x = x_hi * 2^32 + x_lo, and y = y_hi * 2^32 + y_lo.

    Then x * y == (x_hi * y_hi) * 2^64 + (x_hi * y_lo + x_lo * y_hi) * 2^32 + (x_lo * y_lo).

    The high 64 bits of that product can, therefore, be computed as follows:

    long x_hi = x >>> 32;
    long y_hi = y >>> 32;
    long x_lo = x & 0xFFFFFFFFL;
    long y_lo = y & 0xFFFFFFFFL;
    long prod_hi = (x_hi * y_hi) + ((x_ hi * y_lo) >>> 32) + ((x_lo * y_hi) >>> 32);
    

提交回复
热议问题