Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship between 2’s complement and IEEE754?

I used to think that all numbers are stored in computers in 2’s complement format. And there is no -0 in 2’s complement. But in IEEE754, there are both +0 and -0. And I read that in JavaScript, all numbers are IEEE754. So now I am confused. What’s more, in JavaScript, ~a = -a -1. I used to think it was caused by the change of 2’s complement of number a. But if every number in JavaScript is stored as IEEE754, how can we convert it as 2’s complement?

like image 520
T.T Avatar asked Sep 05 '25 02:09

T.T


1 Answers

JavaScript cheats: It represents numbers using the IEEE-754 basic 64-bit binary floating-point format but converts them to 32-bit integers for bitwise operations and then converts them back.

JavaScript is an implementation of ECMAScript. The ECMAScript 2018 Language Specification (9th edition, June 2018) specifies the unary ~ operator in clause 12.5.8 (shown as 12.5.10 in the table of contents but 12.5.8 in the text!). The relevant part is:

UnaryExpression : ~ UnaryExpression
1. Let expr be the result of evaluating UnaryExpression.
2. Let oldValue be ? ToInt32(? GetValue(expr)).
3. Return the result of applying bitwise complement to oldValue. The result is a signed 32-bit integer.

The ToInt32 operation truncates the number to an integer (removing any fraction part, rounding toward zero) and then maps the number to the interval [−231, +231) modulo 232.

like image 53
Eric Postpischil Avatar answered Sep 07 '25 21:09

Eric Postpischil