Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

convert int to char?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Can you convert an int to a char???? or a long to a char?
 
Check if your library has the itoa() function. If it doesnt you will have to write your own version or download it from the web.

cheers
amit
crazy_indian@lycos.com

to bug is human to debug devine
 
Hi

Converting an int or long to a char. If you are talking about the values themselves, if they fit the range of char (-128 to 127) you're fine just assigning them:

long lv = 100;
int iv = 100;
char cv = lv;

The compiler might complain about truncating, but that is fine, as you want to do this.

If you're talking about "converting to character string", try the sprintf() function, or better, snprintf() (may not be present on your system).

char buffer[1024];
snprintf(buffer,1024,"%ld %d\n",lv,iv);

fills the buffer with "100 100"

HTH
Pieter
 
hai friend,
i have an idea that is
sprintf(buff,"%d",i); for int var
sprintf(buff,"%ld",l) for long var

or
itoa(); for int
ltoa() for long in "stdlib.h"
bye..
 
converting an "int" or "long" value to a char is pretty easy.Here is one of the way that you can use to do it:

/* for an int */
int var;
char c;
c = (char)var;

/* for a long */
long var;
char c;
c = (char)var;
 
why not try our own implementation!!!!
main()
{
char s[6];//int cant exceed 6
int n;
scanf("%d",&n);
conv(n,q);
strrev(q);
printf("%s",q);
}

int conv(int n,char *s)
{
if(n){
conv(n/10,s+1);
*s=n%10+'0';
} else *s='\0';
}

???can someone suggest a recusive version that does n't require reversing at the end
 
hey leibnitz....u should have tried before u submit ,it 's coming out wierd....see the sizes of char and int are by different so u cant attempt that way
 
Why should you reinvent the wheel? Just use sprintf or snprintf, which have already been mentioned above. //Daniel
 
hey doing things our way is more thrilling....rememeber we are programmers... suggest something better than cvrmurthy
 
I'am sorry to say that cvrmurthy,but there is nothing weird with my code and it is the simplest way to do it.
If you are having weird results,please post your code and the weird outputs that you are getting.

Here is an example of the technic that i have sugest:

Code:
#include<stdio.h>

void main()
{
	int var = 36;
	char c;

	c = (char)var;

	printf(&quot;%c&quot;,c);
}

output: $

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top