4 ms·
unsigned char r(unsigned char num) { return num % 10; } https://godbolt.org/g/26HfQk https://godbolt.org/g/26HfQk
by kwillets 8y ago
unsigned char r(unsigned char num) {
return num % 10;
}
https://godbolt.org/g/26HfQk https://godbolt.org/g/26HfQk
- plpot 8y agoWhat you see there is the insane amount of complexity to create a high level feature of C: functions, plus compiler optimizations. What I don't understand about this argument is that you are calling C a high-level language because of compiler optimizations. I can write code in assembler, or in LLVM SSA, and still use software to optimize it beyond recognition.
- 1ris 8y agoOr compile this with clang and -msse4.2 -O2 // https://codereview.stackexchange.com/questions/38182 // https://codereview.stackexchange.com/a/38184 // Definition: Count number of 1's and 0's from integer with bitwise operation // 2^32 = 4,294,967,296 // unsigned int 32 bit #include<stdio.h> int CountOnesFromInteger(unsigned int); int main() { unsigned int inputValue; short unsigned int onesOfValue; printf("Please Enter value (between 0 to 4,294,967,295) : "); scanf("%u",&inputValue); onesOfValue = CountOnesFromInteger(inputValue); printf("\nThe Number has \"%d\" 1's and \"%d\" 0's",onesOfValue,32-onesOfValue); } // Notice the popcnt int CountOnesFromInteger(unsigned int value) { int count; for (count = 0; value != 0; count++, value &= value-1); return count; }
- kwillets 8y agoI've seen this and others, but they're brittle. Terminating that count loop for any other reason, for example, will break it. There's another one for reversing bytes in an integer, but I ended up hard-coding the intrinsic due to brittleness.
- waynecochran 8y agoYes. this is doing to infamous division by 10 using bit shifts as you will find in hacker's delight: http://www.hackersdelight.org/divcMore.pdf http://www.hackersdelight.org/divcMore.pdf. You may notice that when you divide num by 10 you get a quotient q and a remainder r: num = q*10 + r Once you get q, you can solve for r as r = num - q*10 So this is how you get r and q: q = (num >> 1) + (num >> 2); q = q + (q >> 4); q = q + (q >> 8); q = q + (q >> 16); q = q >> 3; r = num - q*10; q = q + ((r + 6) >> 4) voila!
- kwillets 8y agoYep, 205/2048 = .10009.. This is something I'm actually using, as I'm serializing small int's (0-99). For those it all fits in 16 bits.