1
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??

asked Jun 3, 2011 at 17:09
1
  • We don't. Extending Array.protoype is a bad idea. Commented Jun 3, 2011 at 17:12

3 Answers 3

2

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.

answered Jun 3, 2011 at 17:20
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Jun 3, 2011 at 17:12

4 Comments

Yes i'm aware of that. but what is the purpose of these methods??
i mean why use bitwise operations here??
@DrStrangeLove OK.. I answer again
What is the purpose of getting the lowest 8 bit of num?? optimization?? Why push16 and push32 methods require more than one argument??
0

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.

answered Jun 3, 2011 at 17:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.