stringcharasciistcodesys

How to get ASCII code of char in Codesys?


I need to get a byte code of char in Codesys (using ST language). Is there a way to do it?

For example, in c++ it is quiet straightforward:

int c = 'h';

Solution

  • There are few ways to do that but concept is the same. You convert it to BYTE.

    VAR
        sTest: STRING(1) := 'h';
        bChar: BYTE;
    END_VAR
    
    bChar := STRING_TO_BYTE(sTest);
    

    But I like most use pointers. Here is example of function that return ASCII code of given character in a string.

    FUNCTION STRING_TO_ASCII: BYTE
        VAR_INPUT
            pbIn: POINTER TO BYTE;
            bCharNum: BYTE; (* Character number in a string start with 0 *)
        END_VAR
        pbIn := pbIn + bCharNum;
        STRING_TO_ASCII := pbIn^;
    END_FUNCTION
    

    Now you can use it in program

    VAR
        sTest: STRING(250) := 'Hello Wold!';
        bChar: BYTE;
    END_VAR
    
    bChar := STRING_TO_ASCII(sTest, 0); (* Character H *)
    bChar := STRING_TO_ASCII(sTest, 1); (* Character e *)