D
Dancefire
Hi, everyone
It might be a simple question, but I really don't know the answer.
char c = '1';
cout << c;
The above code will only output a '1' rather than 0x31;
If I use int cast, it can show the number:
cout << (int) c;
however, if the c is > 0x80, which might be a part of MBCS(multibyte
character set) string, such as :
const char* cc = "\xba\xba";
cout << hex << "0x" << (int)cc[0] << ", 0x" << (int)cc[1] << endl;
it will extend negative bit, and will output as:
0xFFFFFFBA, 0xFFFFFFBA
I currently use a stupid way to avoid extending the negative bit and
show the number of a simple char by double casting:
const char* cc = "\xba\xba";
cout << hex << "0x" << (unsigned short)((unsigned char)cc[0]) << ",
0x" << (unsigned short)((unsigned char)cc[1]) << endl;
This time the output looks ok. But it doesn't make any sense, since I
only want to output the char as a number, should not so complicated by
double casting.
Did I miss anything? What is the most directly way to use std::cout
output a char as a number?
Thanks.
It might be a simple question, but I really don't know the answer.
char c = '1';
cout << c;
The above code will only output a '1' rather than 0x31;
If I use int cast, it can show the number:
cout << (int) c;
however, if the c is > 0x80, which might be a part of MBCS(multibyte
character set) string, such as :
const char* cc = "\xba\xba";
cout << hex << "0x" << (int)cc[0] << ", 0x" << (int)cc[1] << endl;
it will extend negative bit, and will output as:
0xFFFFFFBA, 0xFFFFFFBA
I currently use a stupid way to avoid extending the negative bit and
show the number of a simple char by double casting:
const char* cc = "\xba\xba";
cout << hex << "0x" << (unsigned short)((unsigned char)cc[0]) << ",
0x" << (unsigned short)((unsigned char)cc[1]) << endl;
This time the output looks ok. But it doesn't make any sense, since I
only want to output the char as a number, should not so complicated by
double casting.
Did I miss anything? What is the most directly way to use std::cout
output a char as a number?
Thanks.