1

I'm creating a tutorial on JavaScript, and as I deal with explaining bitwise operators, etc. How negative numbers are represented in JavaScript keep coming up.

I believe all I need to describe in my tutorial is two's complement, but do I also need to describe one's complement, or is one's complement irrelevant in JavaScript?

How about floating point numbers, positive and negative numbers, in JavaScript?

2
  • All numbers in JS use IEEE 754 64-bit floating point representation, so even x = 4 is a float. However, bitwise operators forcefully convert a number to 32-bit integer, so 3.14 | 0 will produce 3 but also (2 ** 31 - 1) | 0 is 2147483647 yet (2 ** 31) | 0 is -2147483648. Commented Nov 27, 2020 at 5:59
  • 1
    The bit string of any float can be obtained with Array.from(new Uint8ClampedArray(new Float64Array([ 420.69 ]).buffer), (byte) => byte.toString(2).padStart(8, "0")).join(""). Replace Float64Array by Int32Array to inspect integers. The bytes may, however, be reversed, based on endianness. Commented Nov 27, 2020 at 13:15

1 Answer 1

2

All numbers in JavaScript are floating point numbers. The representation rule for negative numbers is the same as IEEE-754.

But when you are using bitwise operators in JavaScript, The operands are converted to signed 32-bit integers automatically.

Sign up to request clarification or add additional context in comments.

2 Comments

Are those 32-bit integers represented in two's complement?
@GregLafrance I believe so.

Your Answer

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.