3 ms·
Ooh, I can write signum in three instructions on PowerPC: divw r4,r3,r3 srawi r3,r3,31 or r3,r3,r4 The equivalent in C: int signum(int x) { r
by ridiculous_fish 12y ago
Ooh, I can write signum in three instructions on PowerPC:
divw r4,r3,r3
srawi r3,r3,31
or r3,r3,r4
The equivalent in C:
int signum(int x) { return (x / x) | (x >> 31); }
This uses the hilariously fun fact that integer division by zero silently gives you zero on PPC.
- unwind 12y agoProbably best to stick to assembly for that, since the C version has lots of undefined behavior (division by zero is UB, as is bitwise shift of a negative number) an optimizing compiler can do what it want with that code. :) I'm not trying to be annoying, but I think there's value in not publishing broken code without at least noting that it is broken. I realize that the code still communicates to humans how to compute signum(), but it's meaningless if compiled which is kind of important sometimes too.