high bits of long multiplication in Java?

前端 未结 7 956
说谎
说谎 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:14

    If either x or y can be negative, you should use Hacker's Delight function (Henry S. Warren, Hacker's Delight, Addison-Wesley, 2nd edition, Fig. 8.2):

    long x_high = x >>> 32;
    long x_low = x & 0xFFFFFFFFL;
    long y_high = y >>> 32;
    long y_low = y & 0xFFFFFFFFL;
    long z2 = x_low * y_low;
    long t = x_high * y_low + (z2 >>> 32);
    long z1 = t & 0xFFFFFFFFL;
    long z0 = t >>> 32;
    z1 += x_low * y_high;
    return x_high * y_high + z0 + (z1 >>> 32);
    

提交回复
热议问题