1. 7
  1.  

  2. 4
    int get_day(long long d) { return d % 100LL; }
    int get_month(long long d) { return (d / 100LL) % 100LL; }
    int get_year(long long d) { return (d / 10000LL); }
    
    1. 2

      I like seeing new approaches to solving string parsing problems for C, C++ and Java. Some similar functions in the standard libraries tend to exhibit poor performance in larger, time-sensitive parsing problems (e.g., parse 100 million values in under 1s), and more alternatives are always appreciated. I’d recommend adding unit tests and a performance comparison vs similar functions from the string library. That is an interesting idea for finding string length, but since it relies on the math library, it might benefit from the fast math compiler flag. For me, the hook is always correctness and performance.

      1. 4

        This is not string parsing though, it takes an int, uses logarithms and floating point math to split out date components and sends it off to printf("%i...") (with a hardcoded ‘0’ rather than using %02i).

        Not really sure of the problem being solved there, especially if the input is already an int and probably something upstream of it already did the string parsing?

        For what its worth, I was able to replace it with:

        $ cat moo.c
        #include <stdio.h>
        
        int main() {
          int date = 20190413;
          printf("%04i-%02i-%02i\n", (int)(date / 10000), (int)((date / 100) % 100), (int)(date % 100));
        }
        

        Maybe am missing something?

        1. 1

          I actually didn’t know about that syntax for fixed formats.

        2. 1

          Thanks! I agree.

          1. 1

            log10/exp10 produces the wrong result (for this purpose) for zero and any negative number.

          2. 1

            I think it’d be faster and simpler to use bit masks.

            day = date & 255 month = date >> 8 & 255

            But I’m unsure what the use case would be.

            1. 1

              If you’re going to use bit masks, no need to waste bits, e.g. date & 31 is enough! Month and date fit into 9 bits, so a 16-bit date would be enough to store 179 years – maybe we should be expecting a Y2079 or 2159 problem…