Lukas Kitsche
Lukas Kitsche

Reputation: 147

How to declare an unsigned int variable in javascript?

This is what I want:

>> var uint n = 0;
<- undefined (output by firefox dev console, I don't know what this means)
>> n;
<- 0;
>> n - 1;
<- 4294967295 (2^32-1)

So how to declare a variable, in javascript, so that it is unsigned? Thanks in advance.

Upvotes: 13

Views: 50892

Answers (3)

Harel Ashwal
Harel Ashwal

Reputation: 1681

Is this what you mean?

var unsigned = someVar >>>0

JavaScript C Style Type Cast From Signed To Unsigned

Upvotes: 24

Sebastian Altamirano
Sebastian Altamirano

Reputation: 37

Every number elevated by two is positive, so...

let uint = number =>  Math.sqrt(Math.pow(number, 2));
console.log(uint(-4)); // 4

Upvotes: -1

Emil S. J&#248;rgensen
Emil S. J&#248;rgensen

Reputation: 6366

If you really need them unsigned then check Uint32Array on MDN.

However, since you don't really gain anything from your values being unsigned, perhaps a simple modulus operation would be better?

//Create var as array of length 1
var arr = new Uint32Array(1);
//set first value to 1
arr[0] = 1;
//output contents
console.log(arr);
//substract to "negative"
arr[0] -= 2;
//output contents
console.log(arr);

Modulus

//Object with setter, to make it simpler
var my_obj = Object.create({
  //This is our value
  value: 0
}, {
  //This is our setter
  set: {
    value: function(a) {
      //Make incoming value a modulus of some integer
      //I just use 1000 for the example
      var max = 1000;
      a = a % max;
      //Force a positive
      while (a < 0) {
        a += max;
      }
      //Set value
      this.value = a;
      //Return object regerence for chaining
      return this;
    }
  }
});
console.log("0:", my_obj.value);
my_obj.set(500);
console.log("500:", my_obj.value);
my_obj.set(-0);
console.log("-0:", my_obj.value);
my_obj.set(-1);
console.log("-1:", my_obj.value);
my_obj.set(-100);
console.log("-100:", my_obj.value);
my_obj.set(-0);
console.log("-0:", my_obj.value);

Or with a function:

function modulusMax(value, a) {
  //Make incoming value a modulus of some integer
  //I just use 1000 for the example
  var max = 1000;
  a = a % max;
  //Force a positive
  while (a < 0) {
    a += max;
  }
  //Set value
  value = a;
  //Return object regerence for chaining
  return value;
}

var v = 0;

console.log("0:", modulusMax(v, 0));
console.log("500:", modulusMax(v, 500));
console.log("-0:", modulusMax(v, -0));
console.log("-1:", modulusMax(v, -1));
console.log("-100:", modulusMax(v, -100));
console.log("1100:", modulusMax(v, 1100));
console.log("-0:", modulusMax(v, -0));

Upvotes: 13

Related Questions