Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an uint64 to string in C++

Tags:

c++

string

uint64

What's the easiest way to convert an uint64 value into a standart C++ string? I checked out the assign methods from the string and could find no one that accepts an uint64 (8 bytes) as argument.

How can I do this?

Thanks

like image 953
Bilthon Avatar asked Jun 24 '10 19:06

Bilthon


2 Answers

The standard way:

std::string uint64_to_string( uint64 value ) {
    std::ostringstream os;
    os << value;
    return os.str();
}

If you need an optimized method, then you may use this one:

void uint64_to_string( uint64 value, std::string& result ) {
    result.clear();
    result.reserve( 20 ); // max. 20 digits possible
    uint64 q = value;
    do {
        result += "0123456789"[ q % 10 ];
        q /= 10;
    } while ( q );
    std::reverse( result.begin(), result.end() );
}
like image 153
Frunsi Avatar answered Sep 29 '22 10:09

Frunsi


#include <sstream>

std::ostringstream oss;
uint64 i;
oss << i;
std:string intAsString(oss.str());
like image 43
Randolpho Avatar answered Sep 29 '22 08:09

Randolpho