简体   繁体   English

c++ 如何将字符转换为十六进制

[英]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?这次如何将ch更改为hex

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:例如,如果您尝试将单个字符转换为十六进制以使用 if 进行数学运算,则可以使用以下语句将 ascii 字符表示转换为其实际数字:

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.并使用 y 作为您的新号码。 If you need to do it for more then one digit you can place this in a loop.如果您需要多于一位数,您可以将它放在一个循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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