简体   繁体   中英

c++ how to convert a character to hex

I know that when outputting hex I can use

cout<<hex<<(unsigned int)(unsigned 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.

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