PATurmel
PATurmel

Reputation: 97

Is it possible to set a javascript number to 32 bits?

Is it possible to set a javascript number to 32 bits instead of 64?

Upvotes: 3

Views: 6242

Answers (2)

AdenFlorian
AdenFlorian

Reputation: 119

I came across this question when looking to take javascript numbers and "convert" them to 32 bits, because the Web Audio API stores AudioParam values as 32 bits, and I was having issues comparing my values from my application's state with the AudioParam value, and them not being the same.

I eventually learned about Math.fround(), which will round your number to:

the nearest 32-bit single precision float representation of a Number

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround

So, depending on your use case, this might work for you.

Upvotes: 3

punstress
punstress

Reputation: 1196

According to JS Definitive Guide if you do bitwise operations, the number converts automatically to 32 bits:

The bitwise operators expect integer operands and behave as if those values were represented as 32-bit integers rather than 64-bit floating-point values. These operators convert their operands to numbers, if necessary, and then coerce the numeric values to 32-bit integers by dropping any fractional part and any bits beyond the 32nd. The shift operators require a right-side operand between 0 and 31. After converting this operand to an unsigned 32-bit integer, they drop any bits beyond the 5th, which yields a number in the appropriate range.

All you have to do is perform a bitwise operation on the number, such as ORing it with 0. You will have the same number but it will be 32 bits.

Upvotes: 5

Related Questions