Bilthon
Bilthon

Reputation: 2511

Converting an uint64 to string in C++

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

Upvotes: 6

Views: 34631

Answers (7)

davidvandebunte
davidvandebunte

Reputation: 1486

C++11 standardized the to_string function mentioned by Frunsi as std::to_string:

#include <string>

int main()
{
  uint64_t value = 128;
  std::string asString = std::to_string(value);
  return 0;
}

Upvotes: 5

Randolpho
Randolpho

Reputation: 56391

#include <sstream>

std::ostringstream oss;
uint64 i;
oss << i;
std:string intAsString(oss.str());

Upvotes: 11

Edward Strange
Edward Strange

Reputation: 40859

std::string converted(reinterpret_cast<char*>(&my_int64),
                      reinterpret_cast<char*>((&my_int64)+1));

Upvotes: -1

Frunsi
Frunsi

Reputation: 7147

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() );
}

Upvotes: 13

Greg Domjan
Greg Domjan

Reputation: 14105

more descriptive than streams I think is lexical_cast

uint64 somevalue;
string result = boost::lexical_cast<string>(somevalue);

Upvotes: 9

Patrick
Patrick

Reputation: 23619

C++: Use a stringstream

C: sprintf (buffer,"%I64ld",myint64);

Upvotes: 4

Chris
Chris

Reputation: 1333

I think you want to output it to a stringstream. Start here:

http://www.cppreference.com/wiki/io/sstream/start

Upvotes: 4

Related Questions