Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the correct result of boost::lexical_cast and std::to_string for unsigned char

Tags:

c++

c++11

What's the correct result of below cast from char to string?

I heard that old boost version 1.46 lexical_cast output was 56, I don't have that version near me that I can't test it. But boost library(1.49) output is: 8

  unsigned char c= 56;
  std::string s = boost::lexical_cast<std::string>(c);
  std::cout << "boost::lexical_cast: " << s << std::endl;

C++11 to_string output is: 56

  std::cout << "std::to_string: " << std::to_string(c) << std::endl;
like image 562
billz Avatar asked Nov 30 '22 21:11

billz


2 Answers

Both are correct. to_string does not care that c is of type char, it will read the number in it and cast it into string.

On the other hand, lexical_cast<std::string> seems to interpret variables of type char as an ascii value. 56 is the ascii value of 8.

like image 38
Thomas Ruiz Avatar answered Jan 12 '23 01:01

Thomas Ruiz


std::to_string only provides overloads for numeric types, probably resolving to the unsigned version in this case. lexical_cast, OTOH, relies on std::ostream::operator<< to perform the conversion, thus treating c as a character.

like image 120
Marcelo Cantos Avatar answered Jan 11 '23 23:01

Marcelo Cantos