CommonBits.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import Double from '../../../../java/lang/Double'
  2. import Long from '../../../../java/lang/Long'
  3. export default class CommonBits {
  4. constructor() {
  5. this._isFirst = true
  6. this._commonMantissaBitsCount = 53
  7. this._commonBits = new Long()
  8. this._commonSignExp = null
  9. }
  10. getCommon() {
  11. return Double.longBitsToDouble(this._commonBits)
  12. }
  13. add(num) {
  14. const numBits = Double.doubleToLongBits(num)
  15. if (this._isFirst) {
  16. this._commonBits = numBits
  17. this._commonSignExp = CommonBits.signExpBits(this._commonBits)
  18. this._isFirst = false
  19. return null
  20. }
  21. const numSignExp = CommonBits.signExpBits(numBits)
  22. if (numSignExp !== this._commonSignExp) {
  23. this._commonBits.high = 0 | 0
  24. this._commonBits.low = 0 | 0
  25. return null
  26. }
  27. this._commonMantissaBitsCount = CommonBits.numCommonMostSigMantissaBits(this._commonBits, numBits)
  28. this._commonBits = CommonBits.zeroLowerBits(this._commonBits, 64 - (12 + this._commonMantissaBitsCount))
  29. }
  30. toString() {
  31. if (arguments.length === 1) {
  32. const bits = arguments[0]
  33. const x = Double.longBitsToDouble(bits)
  34. const numStr = Long.toBinaryString(bits)
  35. const padStr = '0000000000000000000000000000000000000000000000000000000000000000' + numStr
  36. const bitStr = padStr.substring(padStr.length - 64)
  37. const str = bitStr.substring(0, 1) + ' ' + bitStr.substring(1, 12) + '(exp) ' + bitStr.substring(12) + ' [ ' + x + ' ]'
  38. return str
  39. }
  40. }
  41. getClass() {
  42. return CommonBits
  43. }
  44. get interfaces_() {
  45. return []
  46. }
  47. static getBit(bits, i) {
  48. const mask = (1 << (i % 32))
  49. if (i < 32) return (bits.low & mask) !== 0 ? 1 : 0
  50. return (bits.high & mask) !== 0 ? 1 : 0
  51. }
  52. static signExpBits(num) {
  53. return num.high >>> 20
  54. }
  55. static zeroLowerBits(bits, nBits) {
  56. let prop = 'low'
  57. if (nBits > 32) {
  58. bits.low = 0 | 0
  59. nBits %= 32
  60. prop = 'high'
  61. }
  62. if (nBits > 0) {
  63. const mask = (nBits < 32) ? (~((1 << nBits) - 1)) : 0
  64. bits[prop] &= mask
  65. }
  66. return bits
  67. }
  68. static numCommonMostSigMantissaBits(num1, num2) {
  69. let count = 0
  70. for (let i = 52; i >= 0; i--) {
  71. if (CommonBits.getBit(num1, i) !== CommonBits.getBit(num2, i)) return count
  72. count++
  73. }
  74. return 52
  75. }
  76. }