Home > Forum > IEC 61131 Programming (LogicLab) > Converting an INT variable to a String
tagged: INT TO STRING CONVERSION
- This topic has 1 replies, 2 participants and was last updated 1 year, 5 months ago da Sergio Bertana.
-
AuthorPost
-
November 9, 2022 at 6: 06 pm #68561Giuseppe RomanoParticipant
I would need to create a text message consisting of a fixed part in String format and a numeric variable in INT format. Coming from embedded programming in C, I had thought of the simple solution of converting the INT variable into a String and then concatenating it with the first part of the message or the already available String. Exemplifying:
String1: = 'your number is:' (String Variable)
counter: = 1 (INT variable)
MessageFinale = String1 & INT_TO_STR (counter) - string type result variable
In the example the INT_TO_STR () function would be the function I would need. I do not find anything like this in the manual and on the forum, except for the SysVsnprintf function which I have not yet figured out if it can be used for this purpose.
Could you please give me some information on this? Thank you
November 10, 2022 at 9: 30 am #68564Sergio BertanaAdministrator ForumYes its the function SysVsnprintf is what you have to use, since you have experience of programming in C language the function behaves like the snprintf() del C. The only difference is that the arguments cannot be variables but must always be a single argument whose type must be defined.
Coming to your need, if you look in the manual you will find many examples of use of this function but here is an example for your need.
PROGRAM MyProgram VAR i : UDINT; (* Auxiliary variable *) Counter : ARRAY[0..1] OF UINT := [10, 20]; (* Counter value *) Message : STRING[ 32 ]; (* Final message *) END_VAR // Esempio di concatenazione stringhe con funzioni. i:=SysVsnprintf(ADR(Message), SIZEOF(Message), ADR('Counter[0]: %d'), UINT_TYPE, ADR(Counter[0])); //'Counter[0]: 10' i:=SysCVsnprintf(ADR(Message), SIZEOF(Message), ADR(', Counter[1]: %d'), UINT_TYPE, ADR(Counter[1])); //'Counter[0]: 10, Counter[1]: 20' // Esempio di concatenazione stringhe con operatori di conversione. Message:=CONCAT('Counter[0]: ', TO_STRING(Counter[0])); //'Counter[0]: 10' Message:=CONCAT(Message, ', Counter[1]: '); //'Counter[0]: 10, Counter[1]: ' Message:=CONCAT(Message, TO_STRING(Counter[1])); //'Counter[0]: 10, Counter[1]: 20' // [End of file]
As you can see I got the same result using the functions or the string conversion operators. In the example I also visualized how to make a concatenation of values, the snprintf () function of C would have allowed you to do everything in a single line of code:
i=snprintf(Message, SIZEOF(Message), "Counter[0]: %d, Counter[1]: %d", Counter[0], Counter[1]);
-
AuthorPost
- You must be logged in to reply to this topic.