Bill Evans at Mariposa
Bill Evans at Mariposa

Reputation: 3848

sbcl: encoding and decoding characters without actual I/O

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.

Upvotes: 1

Views: 519

Answers (2)

Svante
Svante

Reputation: 51501

For portable code, use babel, available from Quicklisp, which has string-to-octets and octets-to-strings like SBCL.

Upvotes: 2

jkiiski
jkiiski

Reputation: 8421

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"

Upvotes: 3

Related Questions