emul/mini/src/main/resources/org/apidesign/vm4brwsr/emul/lang/java_lang_Number.js
author Martin Soch <Martin.Soch@oracle.com>
Mon, 28 Jan 2013 00:15:38 +0100
brancharithmetic
changeset 594 035fcbd7a33c
parent 593 b42911b78a16
child 607 9e4d0019a9eb
permissions -rw-r--r--
using Number for as a base for Long number type
     1 // empty line needed here
     2 Number.prototype.add32 = function(x) { return (this + x) | 0; };
     3 Number.prototype.sub32 = function(x) { return (this - x) | 0; };
     4 Number.prototype.mul32 = function(x) { 
     5     return (((this * (x >> 16)) << 16) + this * (x & 0xFFFF)) | 0;
     6 };
     7 
     8 Number.prototype.toInt8 = function()  { return (this << 24) >> 24; };
     9 Number.prototype.toInt16 = function() { return (this << 16) >> 16; };
    10 
    11 Number.prototype.next32 = function(low) {
    12   if (this === 0) {
    13     return low;
    14   }
    15   var l = new Number(low);
    16   l.hi = this;
    17   return l;
    18 };
    19 
    20 Number.prototype.high32 = function() { 
    21     return this.hi ? this.hi : (Math.floor(this / 0xFFFFFFFF)) | 0;
    22 };
    23 Number.prototype.toInt32 = function() { return this | 0; };
    24 Number.prototype.toFP = function() {
    25     return this.hi ? this.hi * 0xFFFFFFFF + this : this;
    26 };
    27 Number.prototype.toLong = function() {
    28     var hi = (this > 0xFFFFFFFF) ? (Math.floor(this / 0xFFFFFFFF)) | 0 : 0;
    29     return hi.next32(this % 0xFFFFFFFF);
    30 }
    31 
    32 Number.prototype.add64 = function(x) {
    33     var low = this + x;
    34     carry = 0;
    35     if (low > 0xFFFFFFFF) {
    36         carry = 1;
    37         low -= 0xFFFFFFFF;  // should not here be also -1?
    38     }
    39     var hi = (this.high32() + x.high32() + carry) & 0xFFFFFFFF;
    40     return hi.next32(low);
    41 };
    42 
    43 Number.prototype.div64 = function(x) {
    44     var low = Math.floor(this.toFP() / x.toFP()); // TODO: not exact enough
    45     if (low > 0xFFFFFFFF) {
    46         var hi = Math.floor(low / 0xFFFFFFFF) | 0;
    47         return hi.next32(low % 0xFFFFFFFF);
    48     }
    49     return low;
    50 };
    51 
    52 Number.prototype.shl64 = function(x) {
    53     if (x > 32) {
    54         var hi = (this << (x - 32)) & 0xFFFFFFFF;
    55         return hi.next32(0);
    56     } else {
    57         var hi = (this.high32() << x) & 0xFFFFFFFF;
    58         var low_reminder = this >> x;
    59         hi |= low_reminder;
    60         var low = this << x;
    61         return hi.next32(low);
    62     }
    63 };
    64 
    65 Number.prototype.compare64 = function(x) {
    66     if (this.hi == x.hi) {
    67         return (this == x) ? 0 : ((this < x) ? -1 : 1);
    68     }
    69     return (this.hi < x.hi) ? -1 : 1;
    70 };