3

Is there any method to convert UTF-8 to UTF-16 BE in VBscript?

I have this following code, but converts only into UTF-16 LE. I need the output be in UTF-16 BE.

Sub Utf8ToUtf16Le(fileIn,fileOut) Set FSO = CreateObject("Scripting.FileSystemObject") Set oStream = CreateObject ("ADODB.Stream") With oStream .Open .Type = adTypeText .Charset = "utf-8" .LoadFromFile fileIn FSO.OpenTextFile(fileOut, 2, True, True).Write .ReadText .Close End With End Sub 

    1 Answer 1

    5
    Sub Utf8ToUtf16Le(fileIn,fileOut) Const adTypeText = 2 Const adSaveCreateOverWrite = 2 Dim inputStream Set inputStream = CreateObject("ADODB.Stream") With inputStream .Open .Type = adTypeText .Charset = "utf-8" .LoadFromFile fileIn .Position = 0 End With With CreateObject("ADODB.Stream") .Open .Type = adTypeText .Charset = "utf-16be" .WriteText inputStream.ReadText .Position = 0 .SaveToFile fileOut, adSaveCreateOverWrite .Close End With inputStream.Close End Sub 

    If the BOM is needed in the output, we can explicitly add it with

     .Charset = "utf-16be" .WriteText ChrW(&hFEFF) .WriteText inputStream.ReadText 

    or, as pointed by Kul-Tigin, we can change the .Charset property from utf-16be to unicodeFEFF.

    3
    • Thank you! That worked very well! But I have one question: why my fileOut does not come with byte order mark? Not that I needed, I just want to understand...
      – skrenato
      CommentedApr 3, 2017 at 16:01
    • @skrenato, just guessing, but as by default all vbs strings are UTF-16 probably the encoder does not consider the BOM is needed. If at some point you need it, just add .WriteText ChrW(&hFEFF) before the .WriteText inputStream.ReadText
      – MC ND
      CommentedApr 3, 2017 at 16:28
    • 1
      @skrenato replace the charset utf-16be with unicodeFEFF then it will work as you expect.
      – Kul-Tigin
      CommentedApr 3, 2017 at 17:02

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.