DrStrangeLove
DrStrangeLove

Reputation: 11557

Array new methods

Array.prototype.push8 = function (num) {
    this.push(num & 0xFF);
};

Array.prototype.push16 = function (num) {
    this.push((num >> 8) & 0xFF,
              (num     ) & 0xFF  );
};
Array.prototype.push32 = function (num) {
    this.push((num >> 24) & 0xFF,
              (num >> 16) & 0xFF,
              (num >>  8) & 0xFF,
              (num      ) & 0xFF  );
};

What does this code mean?? from here. Why do we need new methods for Array??

Upvotes: 1

Views: 276

Answers (3)

wong2
wong2

Reputation: 35720

answer again...
this.push(num & 0xFF);
means to get the lowest 8 bit of num, and append it to the array.
For example, if num is 999, then it is 1111100111 in binary number,
then num & 0xFF is:
111100111
011111111


011100111

push16 and push32 are the same.

Upvotes: 1

nrabinowitz
nrabinowitz

Reputation: 55688

I'm not sure what the context of these functions is in the particular project you're looking at, but the effects are:

  • Array.prototype.push8 - add the least significant byte of the submitted number to the array.

  • Array.prototype.push16 - add the two least significant bytes of the submitted number to the array as separate elements.

  • Array.prototype.push32 - add the four least significant bytes of the submitted number to the array as separate elements.

Upvotes: 0

bjornd
bjornd

Reputation: 22943

This is the methods to pack numbers in array. Consider array as a sequence of bytes. Then push8 will add the lowest 8 bits of number to the one cell of array, push16 will add the lowest 16 bits to the to cells of array and push32 will do the same with 32 bits of number and 4 array's cells.

push8(256);
259  = 0000 0001 0000 0011
0xFF = 0000 0000 1111 1111 
&
     = 0000 0000 0000 0011

So 3 will ba added to array.

Upvotes: 2

Related Questions