Search code examples
c++bit-manipulationutc

uint64 UTC time


I have a UTC date time without the formatting stored in a uint64, ie: 20090520145024798 I need to get the hours, minutes, seconds and milliseconds out of this time. I can do this very easily by converting it to a string and using substring. However, this code needs to be very fast so I would like to avoid string manipulations. Is there faster way, perhaps using bit manipulation to do this? Oh by the way this needs to be done in C++ on Linux.


Solution

  • uint64 u = 20090520145024798;
    unsigned long w = u % 1000000000;
    unsigned millisec = w % 1000;
    w /= 1000;
    unsigned sec = w % 100;
    w /= 100;
    unsigned min = w % 100;
    unsigned hour = w / 100;
    unsigned long v = w / 1000000000;
    unsigned day = v % 100;
    v /= 100;
    unsigned month = v % 100;
    unsigned year = v / 100;
    

    The reason why this solution switches from uint64 u to unsigned long w (and v) in the middle is that the YYYYMMDD and HHMMSSIII fit to 32 bits, and 32-bit division is faster than 64-bit division on some systems.