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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

char to char array

Status
Not open for further replies.

manichandra

Technical User
Feb 6, 2012
19
US
is there any possibility to convert a char to a char array
example :
here is char a ='163';
char data[16];
i want to input the value of 'a' to 'data' as
data[0]='1'
data[1]='6'
data[2]='3'
data[3]='\0'
 
1. Use sprintf:
Code:
char a = 163;
char data[16];
sprintf(data,"%d",a);

2. use itoa() non-standard function:
Code:
char a = 163;
char data[16];
itoa(a,data,10);

3. Remember that if int n is a number 0..9 then '0'+n is a char which represents the corresponded digit in the internal charcode (see the C Language Standard;). It's very good exercise to implement algorithm (~15 minutes) - use % operator to get all number digits (right to left, then reverse string).
 
is converting from a char array to a single char possible ??

char data[]="163" to char data=163

and how to convert from int a=163 to char data[]="163"
and int n =163 to char a = 163

thanks
 
Let's look into char type in C. Values of char type are small

integers - that's all. The range of char values depends on the C

language implementation: the language standard does not specify

whether char values are signed or unsigned integers. As usually,

char values ranges are -128..127 (VC compilers) or 0..255 (BC

compilers).

You may use chars in arithmetical expressions, assign them to int

variables (and vice versa). Constants of char type 'c' are integer

values of correspondent characters which are defined in the

internal (implementation-dependent) charset.

If assigned integer values are out of char type range, only least

significant bits are assigned (this truncation is not an error).

For example:
Code:
char c = 256; /* Don't use this truncation at home. */
if (c == 0) { /* That's true, now c has zero value! */
   /* Did you understand why we came here? */
   if (c == '0') { /* Oops, 0 != '0' */

   }
}

Now let's return to your problem(s). Arbitrary expressions (even with 1-digit number operands) may have arbitrary result values. It's possible to calculate values which do not fit to char range. Yes, you can assign these values to char (with truncation) but what you want to do with this char?

You can convert text to int or char:
Code:
char data[] = "163";
int  x = atoi(data); /* x == 163 */
char c = atoi(data); /* c != 163 now (can you explain why?) */
I'm in doubt that it's useful conversion...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top