Search code examples
encodingabaputf-16

Get UTF-16 code unit at a given index in ABAP


I want to get the UTF-16 code unit at a given index in ABAP.

Same can be done in JavaScript with charCodeAt().

For example "d".charCodeAt(); will give back 100.

Is there a similar functionality in ABAP?


Solution

  • This can be done with class CL_ABAP_CONV_OUT_CE

    DATA(lo_converter) = cl_abap_conv_out_ce=>create( encoding = '4103' ). "Litte Endian
    
    TRY.
        CALL METHOD lo_converter->convert
          EXPORTING
            data   = 'a'
            n      = 1
          IMPORTING
            buffer = DATA(lv_buffer). "lv_buffer will 0061
    CATCH ...
    
    ENDTRY.
    

    Codepage 4102 is for UTF-16 Big endian.

    It is possible to encode not just a single character, but a string as well:

          EXPORTING
            data   = 'abc'
            n      = 3
    

    "n" always stands for the length of the string you want to be encoded. It could be less, than the actual length of the string.