samedi 28 octobre 2017

Effective implementation of conversion small string to uint64_t

#include <cstdint>
#include <cstring>

template<typename T>
T oph_(const char *s){
    constexpr std::size_t MAX = sizeof(T);
    const     std::size_t size = strnlen(s, MAX);

    T r = 0;

    for(auto it = s; it - s < size; ++it)
        r = r << 8 | *it;

    return r;
}

inline uint64_t oph(const char *s){
    return oph_<uint64_t>(s);
}

int main(){
    uint64_t const a = oph("New York City");
    uint64_t const b = oph("Boston International");
    return a > b;
}

I want to convert first 8 characters from const char * to uint64_t so I can easily compare if two strings are greater / lesser.

I am aware that equals will semi-work.

However I am not sure if this is most efficient implementation.

I want the implementation to work on both little and big endian machines.

Aucun commentaire:

Enregistrer un commentaire