简体   繁体   中英

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

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;

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.

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.

The old boost version is incorrect.

The result of lexical_cast is supposed to be the same as streaming to an ostream. So the result of

std::cout << boost::lexical_cast<std::string>(x)

is identical to

std::cout << x

In case of unsigned char that means interpreting x as an ASCII code, for other integer types it will give the same result as itoa . This is because the char types are not considered as arithmetic integers by ostream (see §27.3.6.2 vs §27.3.6.4). The advantage of this approach is that you can output a string by outputting its single chars. If you want the actual numeric value, you can always cast the char to an arithmetic type for output.

to_string on the other hand works like itoa for all integer datatypes, as it does not have an overload for unsigned char . The rationale here is that by calling to_string you already expressed your intent to perform a conversion, ie you are not interested in the character-type quality of the value (which would be the default) but the arithmetic-type quality.

It's a matter of interpretation. If you interpret a char as a small integer you print its code in the current character set; this is what to_string appears to be doing.

If you interpret it as a character to be printed you issue the corresponding character, ie 8 as boost::lexical_cast does.

This isn't char to string, it is "unsigned char" to string. And they are both correct. lexical_cast converts using a stringstream instance while std::to_string is overloaded for unsigned which means unsigned char is promoted to unsigned int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM