C - casting int to char and adding char to char

I am making my first parallel application, but I stick to the basics of C. I need to know how to distinguish int from char, and then how to add one char to another.

That you could help me, I would be glad. Thanks.

+7
source share
5 answers

You can use itoa to convert an integer to a string.

You can use the strcat function to add characters to a line at the end of another line.

If you want to convert an integer to a character, just follow these steps:

int a = 65; char c = (char) a; 

Please note that since characters are smaller than an integer, this casting can lead to data loss. It is better to declare the character variable as unsigned in this case (although you can still lose data).

To make an easy reading about type conversion, go here .

If you still have problems, please comment on this answer.

Edit

Go here for a more suitable example of combining characters.

Also a more detailed link is given below -

Second edit

 char msg[200]; int msgLength; char rankString[200]; ........... // Your message has arrived msgLength = strlen(msg); itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id strncat( msg, rankString, (200 - msgLength) ); // msg now contains previous msg + id // You may loose some portion of id if message length + id string length is greater than 200 

Third editor

Go to this link . Here you will find the implementation of itoa . Use this instead.

+8
source

Listing int to char is done simply by assigning with a type in parentheses:

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

Note. I thought you could lose data (as in the example) because the sizes of the types are different.

Adding characters to characters is not possible (if you do not mean arithmetic, then these are simple operators). You need to use strings, arrays of AKA characters and <string.h> such as strcat or sprintf .

+3
source
 int myInt = 65; char myChar = (char)myInt; // myChar should now be the letter A char[20] myString = {0}; // make an empty string. myString[0] = myChar; myString[1] = myChar; // Now myString is "AA" 

This should all be found in any introduction to Book C or as a result of some basic online search.

+2
source

Dropping an int in char is related to data loss, and the compiler will probably warn you.

Extracting a specific byte from int sounds more reasonable and can be done as follows:

 number & 0x000000ff; /* first byte */ (number & 0x0000ff00) >> 8; /* second byte */ (number & 0x00ff0000) >> 16; /* third byte */ (number & 0xff000000) >> 24; /* fourth byte */ 
+1
source
 int i = 100; char c = (char)i; 

It is not possible to add one char to another. But you can create an array of characters and use it.

0
source

All Articles