问题
In sbcl, when encoding a string using, say, :utf-8, is there a way to encode it to a byte vector without doing actual I/O, similar to clisp's
(EXT:CONVERT-STRING-TO-BYTES string encoding &KEY :START :END)
and also decode with something like clisp's
(EXT:CONVERT-STRING-FROM-BYTES vector encoding &KEY :START :END)
I could crudely approximate this by writing the data to a file with the desired encoding and then rereading it using :iso-8859-1, but that seems to be a dorky longcut.
回答1:
SBCL has the functions SB-EXT:STRING-TO-OCTETS
and SB-EXT:OCTETS-TO-STRING
for this.
CL-USER> (sb-ext:string-to-octets "fööbär" :external-format :utf-8)
#(102 195 182 195 182 98 195 164 114)
CL-USER> (sb-ext:string-to-octets "fööbär" :external-format :iso-8859-1)
#(102 246 246 98 228 114)
CL-USER> (sb-ext:octets-to-string ** :external-format :utf-8)
"fööbär"
CL-USER> (sb-ext:octets-to-string ** :external-format :iso-8859-1)
"fööbär"
回答2:
For portable code, use babel, available from Quicklisp, which has string-to-octets
and octets-to-strings
like SBCL.
来源:https://stackoverflow.com/questions/46260357/sbcl-encoding-and-decoding-characters-without-actual-i-o