Baz
Baz

Reputation: 13175

Convert int8_t to std::string

Is this correct for all C++ compilers? Or should I cast to int first instead?

int8_t i = -128; 
std::string = boost::lexical_cast<std::string>((int16_t)i)

Upvotes: 2

Views: 7575

Answers (1)

111111
111111

Reputation: 16168

You can use the std::to_string function to do this:

 std::int8_t i = -128; 
 std::string s=std::to_string(i);

http://en.cppreference.com/w/cpp/string/basic_string/to_string

NOTE:

I assumed C++11 because fixed width types where only added in C++11

http://en.cppreference.com/w/cpp/types/integer

edit

If this is not C++11 (and you are getting the typedef form somewhere else (C99?)) then you can just provide the source type as a template parameter.

 std::string str=boost::lexical_cast<std::string, int>(i);

http://www.boost.org/doc/libs/1_40_0/libs/conversion/lexical_cast.htm#synopsis

Upvotes: 10

Related Questions