gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > int 2 char

#3285 - jenswa - Fri Feb 21, 2003 8:12 pm

I am having just a 'simple' question,

how to convert an int to a char?
and the other way around?

I've only programmed with flash, in flash you don't need to
declare a variable like int or char, flash does it for you,
since i used these chars as int and ints as chars.

I might have the same situation on the gba, then i would like
to know what do with it.

bye

JJ
_________________
It seems this wasn't lost after all.

#3290 - Vortex - Fri Feb 21, 2003 8:32 pm

Quote:

how to convert an int to a char?


This one will require explict conversion.

int i = 45;
char c = (char) i;

Quote:

and the other way around?


char c = 'A';
int i = c;


Last edited by Vortex on Fri Feb 21, 2003 8:33 pm; edited 1 time in total

#3291 - mbcook - Fri Feb 21, 2003 8:32 pm

Just force a cast. You should note than when going from int->char you can lose information (depending on what's in the int, the size, etc). But here is some code as an example:

Code:

int myInt = 7;
char myChar = 58;

int charToInt = (int) myChar;
char intToChar = (char) myInt;


That's how you do it. Now if you want to covert the number 7 to the character '7', that's a bit different. You do that like this (usually):

Code:

int theNumber = 7;
char theChar;

theChar = (char) theNumber + '0';  // The number 0 in single quotes means it's ascii value

// Now theChar contains '7'


This assumes one thing: theNumber MUST be 0-9. It can't be more, or less. That's up to you to make sure of. The cast is to prevent the compiler from complaining about things.

Does that answer your question? If not, if you can clarify your question better, I'll try to help you better.
_________________
--Michael

#3318 - jenswa - Sat Feb 22, 2003 8:01 pm

Thanks guys!
_________________
It seems this wasn't lost after all.