views:

876

answers:

5

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?

+10  A: 
char c;
int ascii = (int) c;

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?

gimel
+3  A: 

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

char c = 'a';
+3  A: 

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.

Adam Rosenfield
+2  A: 

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.

anon
A: 

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 -

Jeff