Working with binary / bit shifts in JavaScript

I am trying to do some bit-swapping operations and handle binary numbers in JavaScript.

Here is what I am trying to do. The user enters a value, and I do the following with him:

// Square Input and mod with 65536 to keep it below that value
var squaredInput = (inputVal * inputVal) % 65536;
// Figure out how many bits is the squared input number
var bits = Math.floor(Math.log(squaredInput) / Math.log(2)) + 1;
// Convert that number to a 16-bit number using bitshift.
var squaredShifted = squaredInput >>> (16 - bits);

As long as the number is more than 46, it works. When it is less than 46, it does not work. I know the problem is bitrate. Now, based on the C-background, I know that this will be done differently, since all numbers will be stored in 32-bit format (provided that it is int). Does JavaScript do the same (since it vardoesn't type)?

If so, is it possible to store a 16-bit number? If not, can I consider it as 32-bit and perform the required calculations, assuming it is 16-bit?

Note. I am trying to extract the middle 4-bit of a 16-bit value in squaredInput.

Another note: when printing var, it just prints the value without filling, so I can not figure it out. Tried to use parseIntand toString.

thank

+3
source share
2 answers

Are you looking for this?

function get16bitnumber( inputVal ){
   return ("0000000000000000"+(inputVal * inputVal).toString(2)).substr(-16);
}

This function returns the last 16 bits of a value (inputVal*inputVal). With a binary string, you can work with any range of bits.

+1
source

Do not use bit-shift in JS unless you need to. The specifications mention at least four number formats

  • IEEE 754
  • Int32
  • UInt32
  • UInt16

It is really confusing to know what is used when.

, ~ Int32. UInt16, -, String.fromCharCode. - UInt32 Int32.

>>> UInt32.

a >>> b

, :

ToUInt32(a) >>> (ToUInt32(b) & 0x1f)
0

All Articles