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.
We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.
We can convert int to char in java using typecasting. To convert higher data type into lower, we need to perform typecasting. Here, the ASCII character of integer value will be stored in the char variable. To get the actual value in char variable, you can add '0' with int variable.
To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char. the equivalent of the number 65 (It should be the letter A for ASCII).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With