Variable Conversion

Is thier a way to convert a char array into an int and vice versa?
Not that i know of? I think int is for variables and chars are letters.
what are you trying to do?

int - associated with numbers

char - associated with input keys on a keyboard.

Last edited on
On the assumption that you meant interpret a char array as an int array, and vice-versa, yes.

1
2
3
int* intPointer = (int*) charPointer;

char* charPointer = (char*) intPointer;



Remember that an int is four (or eight) times the size of a char, so you will read four char at once and interpret it as an int.
Last edited on
By using a simple typecast. For example:
1
2
char ch = 'A';
int number = int(ch);

More information on typecasting can be found in the tutorial: http://cplusplus.com/doc/tutorial/typecasting/

Now for an entire array you could use a for loop on a newly initialized int or char array.
1
2
3
4
vector<char> chars('A', 10);  //creates a char array of size ten with all 'A'
vector<int> ints(chars.size());  //creates a new array with the same amount of space as the chars array
for(int i=0; i<chars.size(); i++)
   ints[i] = int(chars[i]);


Hope this helps.
man wrote:
atol - convert a string to an integer
strtol - convert a string to a long integer

sprintf - formatted output conversion
Also, stringstream.
Ok since everyone refers to whatever comes to mind I can remind the c++ casters:

1
2
3
4
char c;
int i;
i = static_cast<int>(c);
c = static_cast<char>(i);


If you use c++ use this instead. it's more type safe and more clear.
You don't need any casts at all if you want to assign a char to an int because char is an integral type as well and it's size is guaranteed to be smaller or equal to int.
One way is strtol():
http://cplusplus.com/reference/clibrary/cstdlib/strtol/

Another is using std::istringstream:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <sstream>
#include <iostream>

int main()
{
	const char str[] = "45";

	int i;
	if(std::istringstream(str) >> i)
	{
		// success
		std::cout << "i: " << i << '\n';
	}
}

http://cplusplus.com/reference/iostream/istringstream/
Is Moschops' answer in the right ball park? It's the only one which, to me, fits the wording of the original question. But you never know.

If you are packing and unpacking ints into a char buffer to send over sockets, or into a file which might be read on a machine running a different operating system, then you might have to worry about endianness.

Data sent over sockets should generally be in network byte order (i.e. big-endian).
nickoolsayz, "char" is an integral type like short, int, and long - it is not different or 'special'. Character literals ('A') are of type char and string literals ("A") are of type char*, just as integer literals (1234) are of type int, hence why when you write an integer literal larger than the maximum size of an integer it does not work.
Topic archived. No new replies allowed.