Is there a function that returns the ASCII value of a character? (C++)

自古美人都是妖i 提交于 2019-12-18 14:52:28

问题


I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc...

On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?


回答1:


char c;
int ascii = (int) c;
s2.data[j]=(char)count;

A char is an integer, no need for conversion functions.

Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?




回答2:


You don't need a function to get the ASCII value -- just convert to an integer by an (implicit) cast:

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:

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.




回答3:


If you want to get the ASCII value of a character in your code, just put the character in quotes

char c = 'a';



回答4:


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.




回答5:


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 -



来源:https://stackoverflow.com/questions/845710/is-there-a-function-that-returns-the-ascii-value-of-a-character-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!