3 ms·
This reminds me of an assignment we had in one of my CpE classes. We had to implement a whole bunch of interesting operations using a limited set of operators
by phamilton 16y ago
This reminds me of an assignment we had in one of my CpE classes. We had to implement a whole bunch of interesting operations using a limited set of operators and in as few operations as possible. Favorites:
Absolute value of a signed it:
a= x >> 32
return (a + x)^a
Swap values of two ints without a temporary int:
a^=b
b^=a
a^=b
! operator (boolean not) without any boolean operators:
int a = x | (~x +1);
int b = a >> 31;
return b + 1;
There were a ton of interesting problems. Made for a great assignment.
- andfarm 16y agoAbsolute value of a signed it: a= x >> 32 return (a + x)^a Careful; right-shifting by >= the size of the type is an undefined operation, and might not do what you expect in all cases. (For instance, it might do nothing at all on x86, as integer shifts/rotations in ia32 are all performed modulo 32.)