5 ms·
Well, for one, if true is -1 (using two's complement), then a bunch of conditionals and bit-twiddling become more simple. For instance: x = some_bool ? a
by KMag 8y ago
Well, for one, if true is -1 (using two's complement), then a bunch of conditionals and bit-twiddling become more simple. For instance:
x = some_bool ? a : b;
can be compiled as a branchless:
x = (some_bool & a) | (~some_bool & b);
This is why Forth also represents true as -1.
- pcwalton 8y agoAlso why SIMD fairly universally uses -1 for true. C arguably picked the wrong semantics here. Hardware picks up the slack, however, with the setcc instructions on x86, csinc on AArch64, etc.
- eridius 8y agoThat would only be true if `a` is guaranteed to be a non-zero value though, right? e.g. `x = some_bool ? 0 : 1` would not be able to be represented that way.
- repsilat 8y agoIt works for me. Note that `|` is a bitwise-or (not that it really matters, it just removes a branch) const True = -1 const False = 0 const ternary = (condition, left, right) => \ (condition & left) | (~condition & right) ternary(True, 0, 1) // 0 ternary(False, 0, 1) // 1
- eridius 8y agoOh right, because the right-hand side evaluates to 0 as well in this case. Makes sense.