Reputation: 17743
I am making my first parallel application, but I am stuck with basics of C. I need to know, how to cast int to char and then how to append one char to another.
It you could help me please, i would be glad. Thank you.
Upvotes: 14
Views: 182436
Reputation: 29166
You can use itoa function to convert the integer to a string.
You can use strcat function to append characters in a string at the end of another string.
If you want to convert a integer to a character, just do the following -
int a = 65;
char c = (char) a;
Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned
in this case (though you may still lose data).
To do a light reading about type conversion, go here.
If you are still having trouble, comment on this answer.
Edit
Go here for a more suitable example of joining characters.
Also some more useful 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 Edit
Go to this link. Here you will find an implementation of itoa
. Use that instead.
Upvotes: 16
Reputation: 20262
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h>
functions like strcat
or sprintf
.
Upvotes: 4
Reputation: 24846
int i = 100;
char c = (char)i;
There is no way to append one char to another. But you can create an array of chars and use it.
Upvotes: 0
Reputation: 43498
Casting int
to char
involves losing data and the compiler will probably warn you.
Extracting a particular byte from an int
sounds more reasonable and can be done like this:
number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */
Upvotes: 3
Reputation: 64672
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 intro to C book, or by some basic online searching.
Upvotes: 0