开发者

c++ how to convert a character to hex

I know that when outputting hex I can use

cout<<hex<<(unsigned int)(开发者_如何学Gounsigned char)ch<<endl 

but I am getting a character from standard input by using

cin.read((char*)&ch , sizeof(unsigned char))

how do I change ch to hex this time?


cin.read((char*)&ch , sizeof(unsigned char));
cout << hex << (unsigned int)(ch) << endl;

should work.


if you're trying to convert a single char to hex to do math with if for example, you can convert the ascii char representation to it's actual digit with a statement like:

char x = 'A';
int y = x;
if(y > 47 && y < 58)  //this covers 0-9
   y = y - 48;
else if (y > 64 && y < 71) // this covers A-F
   y = y - 55;

and use y as your new number. If you need to do it for more then one digit you can place this in a loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜