Common lisp 在公共lisp中将整数格式化为字符

Common lisp 在公共lisp中将整数格式化为字符,common-lisp,Common Lisp,将整数格式化为字符序列的最佳方式是什么?我尝试了下面的代码块,它可以工作,但不确定这样做是否正确: (defun int2chars(x) (format t "~c~c~c~c~%" (code-char (ldb (byte 8 24) x)) (code-char (ldb (byte 8 16) x)) (code-char (ldb (byte 8 8) x)) (code-char (ldb (byte 8 0) x))

将整数格式化为字符序列的最佳方式是什么?我尝试了下面的代码块,它可以工作,但不确定这样做是否正确:

(defun int2chars(x)
  (format t "~c~c~c~c~%"
      (code-char (ldb (byte 8 24) x))
      (code-char (ldb (byte 8 16) x))
      (code-char (ldb (byte 8 8) x))
      (code-char (ldb (byte 8 0) x))
      ))

(defun test()
  (let ((x #x75756964))
    (int2chars x)))

(test)

输入为
0x756964
,输出为
uuid

您可以编写一个适用于大于或小于32位整数的函数:

(defun bytes-from-integer (integer)
  (check-type integer (integer 0))
  (loop
    with size = (* 8 (1- (ceiling (integer-length integer) 8)))
    for offset from size downto 0 by 8
    collect (ldb (byte 8 offset) integer)))

(bytes-from-integer #x75756964)
=> (117 117 105 100)

(bytes-from-integer #x7575696475756964)
=> (117 117 105 100 117 117 105 100)
然后,将转换为字符串,如下所示:

(map 'string #'code-char (bytes-from-integer #x75756964))
=> "uuid"


注意:是检查位置是否满足给定类型表达式的宏。上面的位置是
整数
变量,类型是,相当于
(整数0*)
,也称为
无符号字节

谢谢,我把它和
(检查类型整数(整数0))
混淆了,听起来好像
integer
不是函数而是用作函数的?@lucky1928我编辑了答案,添加了一些关于检查类型的备注