Tk Library Source Code

View Ticket
Login
Ticket UUID: 1050608
Title: base64 doesn't encode propertly unicode chars > 0xff
Type: Bug Version: None
Submitter: lave Created on: 2004-10-20 10:26:22
Subsystem: base64 Assigned To: patthoyts
Priority: 5 Medium Severity:
Status: Closed Last Modified: 2005-02-17 22:33:49
Resolution: None Closed By: patthoyts
    Closed on: 2005-02-17 15:33:49
Description:
decode(encode()) is not the identiy operation for
strings with unicode characters > 0x00ff:

% info tclversion
8.4
% source modules/base64/base64.tcl
% string equal \u2019 [::base64::decode
[::base64::encode \u2019]]
0

In the (pure tcl) ::base64 implementation, "binary
scan" is used to get the byte representation of the
characters in the string. This doesn't work for
characters with a unicode representation beyond 0x00ff,
as Tcl itself throws away the unicode high byte:

% set string \u2019
?
% binary scan $string c* X
1
% set X
25
# (this is the low byte 0x19 in dec)

Only variables of the type "bytearray" are handled
correctly, but you will not know from the string
representation if this Tcl object was created as string
or bytearray.

PS: I'm missing a -encoding option to provide the
encoder (decoder) a hint how to get (interpret) the
binary representation of the characters of the string,
as the string to encode is only an array of chars, not
of bytes.
User Comments: patthoyts added on 2005-02-17 22:33:49:
Logged In: YES 
user_id=202636

Added an example to the documentation.

mic42 added on 2004-11-16 09:41:12:
Logged In: YES 
user_id=302287

This is documented:
::base64::encode ?-maxlen maxlen? ?-wrapchar wrapchar? string 
Base64 encodes the given binary string and returns the
encoded result. Inserts the character wrapchar every maxlen
characters of output. wrapchar defaults to newline. maxlen
defaults to 60

A "binary string" is in the essence a string with a
Tcl_ByteArray representation, which is limited to the range
you observed and is quite different from a typical tcl
string. So if you non-binary data to base64 you get
unexpected results.

So if you want to encode utf-8 with base64 you should do:
set string \u2019
set bstring [encoding convertto utf-8 $string]
set b64 [base64::encode $bstring]

for decode:
set bstring [base64::decode $b64]
set string [encoding convertfrom utf-8 $string]

So no real need for a new option, just take care that you
feed "binary strings" to base64.