c++ - Convert basic_string<unsigned char> to basic_string<char> and vice versa -
from following
can turn unsigned char char , vice versa?
it appears converting basic_string<unsigned char> basic_string<char> (i.e. std::string) valid operation. can't figure out how it.
for example functions perform following conversions, filling in functionality of these hypothetical stou , utos functions?
typedef basic_string<unsigned char> u_string; int main() { string s = "dog"; u_string u = stou(s); string t = utos(u); } i've tried use reinterpret_cast, static_cast, , few others knowledge of intended functionality limited.
assuming want each character in original copied across , converted, solution simple
u_string u(s.begin(), s.end()); std:string t(u.begin(), u.end()); the formation of u straight forward content of s, since conversion signed char unsigned char uses modulo arithmetic. work whether char signed or unsigned.
the formation of t have undefined behaviour if char signed char , of individual characters in u have values outside range signed char can represent. because of overflow of signed char. particular example, undefined behaviour not occur.
Comments
Post a Comment