How to convert a list of integer-bytes to a string?

104 Views Asked by At

I have a list of bytes that I want to read as a string. I tried, for example,

(sb-ext:octets-to-string (list 30 40 50))

or

(babel:octets-to-string (list 30 40 50))

but both complain that the input is not "(VECTOR (UNSIGNED-BYTE 8))". So I learned that I can convert my list to a vector via

(coerce (list 30 40 50) 'vector)

but that is still not enough, because coerce returns a "simple-vector" and the elements are still in integer, not "(unsigned-byte 8)".

I looked at the similar questions, but none of them deal with the input being a list of integers. Note that I know that no integer is larger than 255, so overflow is not an issue.

2

There are 2 best solutions below

0
Rainer Joswig On BEST ANSWER

You need to create a vector with an element type (unsigned-byte 8). Vectors can, for example, be created via MAKE-ARRAY and COERCE.

MAKE-ARRAY needs the correct element type:

(sb-ext:octets-to-string
  (make-array 3
              :initial-contents '(30 40 50)
              :element-type '(unsigned-byte 8)))

COERCE needs the correct type to coerce to. The type description VECTOR takes an element type as the second element:

(sb-ext:octets-to-string
  (coerce '(30 40 50)
          '(vector (unsigned-byte 8))))
0
Xach On

(map ‘string ‘code-char list) is a crude way to do it, as long as your integers correspond directly to the encoding presumed by code-char. You can’t do it robustly without thinking about encodings and what the implementation supports and defaults to.