11 years, 2 months ago.

how to go from int to char

i have an integer and i want to split this up into 2 chars this doesnt work:

int i=3145;
char a[2];
a[0]=(char) i;
a[1]=(char)(i >> 8);

anybody has an idea?? thnx

2 Answers

11 years, 2 months ago.

Why do you think it does not work? I think the code is OK. You could even leave out the typecast. What result did you get in a[]?

Accepted Answer
11 years, 2 months ago.

your code is fine, however as your declaration int i =3145 is in decimal, you really need to convert it to hex to see the output. 3145 = c49 in hex, so after execution of the code, a[0]= 49Hex which is 73 and a[1] will be c hex which is 12. This is possibly where the confusion arises.