Today I learned: Javascript and bitwise operations on floats
While working on my own programming language, Letlang (read more about it here), I was faced with an issue.
For the “Proof of Concept”, I decided to have only 64-bits floating point numbers instead of separate integer/float types, just like Javascript. Though , I intend to introduce those separate types later on.
This begs the question: What about bitwise operations?
On integer types, they are pretty straightforward, simply take the bits representation of the integer, and apply the bitwise operations (^
, |
, &
, ~
) on those bits.
But for floats, it’s tricky. Rust (my compilation target) does not define bitwise operations on the f64
type. Indeed, 4.2 | 2.3
does not make a lot of sense.
Applying the same rules of integers on floats would be the wrong thing to do, because in the IEE-754 specification, there are bit representations for Infinity
, NaN
, etc… which could be the result of such operations.
64-bits floating point numbers can represent integers up to 53 bits. Should I apply the bitwise operations on those 53 bits only? What about the signed vs unsigned? Also, when working with bitwise operations, we expect to work with 8 bits, 16 bits, 32 bits or 64 bits integers. 53 bits is so unexpected that it would be beyond wrong to use such a rule.
NB: To me, this is proof that using floats for all numbers is not something to wish for. But I’ll delay that change…