Int to Char
-
- Posts: 10
- Joined: Thu Oct 13, 2005 8:35 am
Int to Char
I'm trying to change a int to char as the title suggests.I'v been getting on fine up untill now but I can't seem to get a function to work that changes an int to char.Think anyone can help me out with this?
- ChaosKnight
- Posts: 142
- Joined: Thu Apr 14, 2005 2:08 am
- Location: Florida, USA
You can be lazy and do this:
Otherwise you will need to bit-shift to get differant values out. A char is 1/4 of an int so an int can contain up to 4 chars in a row. So you could be super duper lazy and get those out like this:
Code: Select all
int i = 0;
char a = (char)i;
Code: Select all
int i = 65535;
char *MyChars = (char *)i;
char a = MyChars[0];
char b = MyChars[1];
char c = MyChars[2];
char d = MyChars[3];
w00t
-
- Posts: 10
- Joined: Thu Oct 13, 2005 8:35 am
This will work if you want the output in hex:
void numtohex8(char *dst, int n)
{
int i;
static char hex[]="0123456789ABCDEF";
for (i=0; i<8; i++)
{
dst=hex[(n>>((7-i)*4))&15];
}
}
Credit for this goes to Abu - it was in his hello world code. You can easily adapt it if you want a shorter output.
Remember to null-terminate the string afterwards : *dst[8] = '\0';
void numtohex8(char *dst, int n)
{
int i;
static char hex[]="0123456789ABCDEF";
for (i=0; i<8; i++)
{
dst=hex[(n>>((7-i)*4))&15];
}
}
Credit for this goes to Abu - it was in his hello world code. You can easily adapt it if you want a shorter output.
Remember to null-terminate the string afterwards : *dst[8] = '\0';
- ChaosKnight
- Posts: 142
- Joined: Thu Apr 14, 2005 2:08 am
- Location: Florida, USA
Fanjita wrote:This will work if you want the output in hex:
void numtohex8(char *dst, int n)
{
int i;
static char hex[]="0123456789ABCDEF";
for (i=0; i<8; i++)
{
dst=hex[(n>>((7-i)*4))&15];
}
}
Credit for this goes to Abu - it was in his hello world code. You can easily adapt it if you want a shorter output.
Remember to null-terminate the string afterwards : *dst[8] = '\0';
If you're linking against newlib, you could also use sprintf....
sprintf(dest_string, "%d", source_int); //For decimal output (also try itoa())
or
sprintf(dest_string, "%x", source_int); // For hex output
Raf.