如何将整数字节列表转换为字符串?

huangapple go评论57阅读模式
英文:

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

问题

我有一个字节列表,我想将其读取为字符串。例如,我尝试了以下代码:

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

或者

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

但都抱怨输入不是"(VECTOR (UNSIGNED-BYTE 8))"。所以我了解到我可以通过以下方式将列表转换为向量:

(coerce (list 30 40 50) 'vector)

但这还不够,因为coerce返回一个"simple-vector",而元素仍然是整数,而不是"(unsigned-byte 8)"。我查看了类似的问题,但没有一个处理输入为整数列表的。请注意,我知道没有任何整数大于255,所以溢出不是问题。

英文:

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.

答案1

得分: 3

你需要创建一个具有 元素类型 (unsigned-byte 8) 的向量。例如,可以通过 MAKE-ARRAYCOERCE 来创建向量。

MAKE-ARRAY 需要正确的 元素类型

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

COERCE 需要正确的类型来强制转换。类型描述 VECTOR元素类型 作为第二个元素:

(sb-ext:octets-to-string
  (coerce '(30 40 50)
          '(vector (unsigned-byte 8))))
英文:

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))))

答案2

得分: 1

(map ‘string ‘code-char list) 是一个粗糙的方法,只要你的整数直接对应于 code-char 所假定的编码,就可以这样做。如果不考虑编码以及实现支持和默认值,就不能稳健地执行此操作。

英文:

(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.

huangapple
  • 本文由 发表于 2023年5月6日 15:53:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定