是否有返回字符的 ASCII 值的函数?(C++)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/845710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a function that returns the ASCII value of a character? (C++)
提问by gimel
I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...
我需要一个函数来返回一个字符的 ASCII 值,包括空格、制表符、换行符等......
On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?
同样,在十六进制、十进制和二进制数之间转换的函数是什么?
回答by gimel
char c;
int ascii = (int) c;
s2.data[j]=(char)count;
A char isan integer, no need for conversion functions.
char是一个整数,不需要转换函数。
Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?
也许您正在寻找将整数显示为字符串的函数 - 使用十六进制、二进制或十进制表示?
回答by Adam Rosenfield
You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:
您不需要函数来获取 ASCII 值——只需通过(隐式)转换转换为整数:
int x = 'A'; // x = 65
int y = '\t'; // x = 9
To convert a number to hexadecimal or decimal, you can use any of the members of the printf
family:
要将数字转换为十六进制或十进制,您可以使用该printf
系列的任何成员:
char buffer[32]; // make sure this is big enough!
sprintf(buffer, "%d", 12345); // decimal: buffer is assigned "12345"
sprintf(buffer, "%x", 12345); // hex: buffer is assigned "3039"
There is no built-in function to convert to binary; you'll have to roll your own.
没有内置函数可以转换为二进制;你必须自己动手。
回答by Adam Rosenfield
If you want to get the ASCII value of a character in your code, just put the character in quotes
如果要获取代码中某个字符的 ASCII 值,只需将该字符放在引号中
char c = 'a';
回答by Adam Rosenfield
You may be confusing internal representation with output. To see what value a character has:
您可能会将内部表示与输出混淆。要查看字符具有什么值:
char c = 'A';
cout << c << " has code " << int(c) << endl;
Similarly fo hex valuwes - all numbers are hexadecimal numbers, so it's just a question of output:
类似的十六进制值 - 所有数字都是十六进制数字,所以这只是一个输出问题:
int n = 42;
cout << n << " in hex is " << hex << n << endl;
The "hex" in the output statement is a C++ manipulator. There are manipulators for hex and decimal (dec), but unfortunately not for binary.
输出语句中的“十六进制”是一个 C++ 操作符。有用于十六进制和十进制 (dec) 的操纵器,但不幸的是没有用于二进制。
回答by Jeff
As far as hex & binary - those are just representations of integers. What you probably want is something like printf("%d",n), and printf("%x",n) - the first prints the decimal, the second the hex version of the same number. Clarify what you are trying to do -
至于十六进制和二进制 - 这些只是整数的表示。您可能想要的是 printf("%d",n) 和 printf("%x",n) 之类的东西 - 第一个打印十进制,第二个打印相同数字的十六进制版本。澄清你想做什么 -