Attribute 'TcEncoding'

Via the pragma you define how a variable of the type STRING should be interpreted.

Syntax: {attribute 'TcEncoding' := 'UTF-8'}

Insertion location: Line above the declaration line of the STRING variable

A variable of the type STRING declared in this way uses the UTF-8 format for the character formatting of the Unicode character set. As with every STRING variable the 0 termination is used here too.

Therefore, in order to support special characters and texts in different languages, the character set is not restricted to the typical character set of the data type STRING (or WSTRING). Instead, the Unicode character set in UTF-8 format is used in conjunction with the data type STRING. This format is generally used in IT.

If the ASCII character set is used, there is no difference between the typical formatting of a STRING and the UTF-8 formatting of a STRING.

With a STRING variable a single character is always stored inside one byte and with a WSTRING variable it is always stored inside two bytes. With the UTF-8 format, however, a single character is stored inside 1 - 4 bytes, depending on which character is concerned. For that reason, the number of characters often doesn't correspond to the size of the variable in bytes.

Sample 1:

The pragma is inserted in the line above the respective variable declaration. It therefore only affects the following declaration line.

VAR
    sMyStringText   : STRING;
    wsMyWStringText : WSTRING;
    {attribute 'TcEncoding':='UTF-8'}
    sMyUTF8Text     : STRING;
END_VAR

Sample 2:

The assignment of a literal requires a help function if the text contains characters that are not defined in the ASCII character set.

VAR
    sMyStringText   : STRING  := 'The dinner costs 30 €.';
    wsMyWStringText : WSTRING := "The dinner costs 30 €.";

    {attribute 'TcEncoding':='UTF-8'}
    sMyUTF8Text1 : STRING  := sLiteral_TO_UTF8('The dinner costs 30 €.');
    {attribute 'TcEncoding':='UTF-8'}
    sMyUTF8Text2 : STRING  := wsLiteral_TO_UTF8("The dinner costs 30 €.");
    {attribute 'TcEncoding':='UTF-8'}
    sMyUTF8Text3 : STRING  := 'Hello World.';

    // verfügbar ab TC3.1 Build 4026
    {attribute 'TcEncoding':='UTF-8'}
    sMyUTF8Text4 : STRING  := UTF8#'The dinner costs 30 €.';
END_VAR

Further help functions for STRING variables and conversion possibilities for UTF-8 are described in the TwinCAT 3 PLC Lib TC2_Utilities documentation.