common-lisp - 在普通 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 test()
  (let ((x #x75756964))
    (int2chars x)))

(test)

输入是0x75756964,输出是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"

备注:CHECK-TYPE是一个检查place 是否满足给定type 表达式的宏。上面,地方是integer变量,类型是(integer 0) ,相当于 (integer 0 *),也称为 unsigned-byte

关于common-lisp - 在普通 lisp 中将整数格式化为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52861031/

相关文章:

lisp - 在 lisp 编程中返回一个值

common-lisp - 当程序有大量输出时,sbcl run-program 挂起

common-lisp - 使用 asdf 和 defpackage 自动解决符号命名冲突

lisp - UVa 10120 礼物?!在 Common Lisp 中?

loops - 在 Common Lisp 循环中定义局部变量

lisp - System.exit(0) 的 lisp 等价物是什么?

lisp - 帮助理解 lisp 中的这一行

lisp - 使用自定义函数 getter 作为 setter 和 setf

list - 如何比较 Lisp 中的两个列表

lisp - 在 clozure common lisp 中读取错误