mardi 25 avril 2017

How to convert unsigned/signed integer/long to C string in an elegant and efficient way?

A lot of people here have asked how to convert unsigned/signed integer/long to C string.

And the most common answer is use sprintf (or snprintf). However, it requires different format strings for different types (e.g. uint32_t, int32_t, uint64_t, int64_t etc).

And I have a function template like this:

// T can only be uint16_t, int16_t, uint32_t, int32_t, uint64_t, int64_t
template <type T>
void foo(char* buffer, T value) {
// write value to buffer
}

I can specialize the function template to solve my problem.

I just wonder whether there is a more elegant and efficient way (i.e. without a temporary buffer like stringstream).

Thanks!

Aucun commentaire:

Enregistrer un commentaire