Blitz3D+ Command Reference

EncodeText ( text$[,code_page] )

Parameters

text$ - the UTF-8 String text to encode

code_page (optional) - target codec:
TEXT_UTF8: strict UTF-8 (default)
TEXT_WINDOWS_1252: Windows-1252
TEXT_SYSTEM_ANSI: the machine's active ANSI code page

Description

Encodes String text into a new owned Bank of bytes using a strict codec.

The bridge from Extended-mode UTF-8 Strings to byte-exact formats: exporting to a legacy tool that expects Windows-1252, building a binary save field with a known encoding, or just getting a String's raw UTF-8 bytes into a Bank for hashing or WriteBankAtomic. The Bank contains only the encoded bytes - no BOM, no terminator.

The codecs are strict, and that is the gotcha worth knowing: a conversion that would lose information is REFUSED rather than patched over. Encoding kanji to TEXT_WINDOWS_1252 does not write "?" like careless converters - EncodeText returns 0 and TextCodecError explains why. Your export code finds out at the border, not when a player reports question marks in their name. TEXT_SYSTEM_ANSI is deliberately machine-dependent and exists only for legacy compatibility - durable new formats should use TEXT_UTF8.

On success the returned Bank is new and owned by you - free it with FreeBank. Any other code page value than the three constants is a programming error. DecodeText is the exact inverse. Note the codecs only convert data - path handling is not affected.

For the full rules, see the Application Data language reference.

Requires Extended mode.

See also: DecodeText, TextCodecError, WriteBankAtomic, FreeBank.

Example

; EncodeText Example
; ------------------
; Requires Extended mode.

; A player name with an accent - one character beyond plain ASCII
name$="Café"
Print "Encoding the player name: "+name
Print ""

; EncodeText returns a new owned Bank of encoded bytes.
; In UTF-8 (the default codec) the é takes two bytes...
utf8_bank=EncodeText(name,TEXT_UTF8)
If utf8_bank=0 Then RuntimeError TextCodecError()
Print "UTF-8:        "+BankSize(utf8_bank)+" bytes"

; ...but the legacy Windows-1252 code page stores it in one
cp1252_bank=EncodeText(name,TEXT_WINDOWS_1252)
If cp1252_bank=0 Then RuntimeError TextCodecError()
Print "Windows-1252: "+BankSize(cp1252_bank)+" bytes"
Print ""

; Show the actual bytes of each encoding
Print "UTF-8 bytes:        "+BankHex(utf8_bank)+"  (c3 a9 = é)"
Print "Windows-1252 bytes: "+BankHex(cp1252_bank)+"    (e9 = é)"

; The returned Banks are owned by us and must be freed
FreeBank cp1252_bank
FreeBank utf8_bank

Print ""
Print "Press any key to close the example"
WaitKey

End

; Render a Bank's bytes as lowercase hex
Function BankHex$(bank)
    hex_text$=""
    For i=0 To BankSize(bank)-1
        hex_text=hex_text+Right(Hex(PeekByte(bank,i)),2)
    Next
    Return Lower(hex_text)
End Function

Index