Common Lisp二进制操作汇总

原创
2019/09/19 10:26
阅读数 1.1K

1. 文件读取

read-byte:

(with-open-file (instream filename
                          :direction :input
                          :element-type 'unsigned-byte
                          :if-exists :supersede)
    (do ((line (read-byte instream nil 'eof) (read-byte instream nil 'eof)))
        ((eq line 'eof) "end of file.")
      (do-something)))

read word:

(defun read-word (s)
  "Reads 16-bit word from the stream"
  (let* ((msb (ash (read-byte s) 8))
         (lsb (read-byte s))
         (word (logior msb lsb)))
    word))

2. 二进制运算

ash:

(ash bin-data num) ;;表示 bin-data*(2^num),num>0为左移位操作;num<0为右移操作
(ash 16 1) > 32
(ash 16 -1) > 8

logior:

(logior 1 2 4 8) => 15 ;;逻辑或运算

logand:

(logand 1 2 4 8) => 0 ;;逻辑与运算

logxor:

(logxor 3 5) => 6 ;;逻辑异或运算

byte:

(byte a b) ;;返回一个cons对象(a . b),意义为从第b个bit开始,取a个bit,设数据共n个字节b为0~2^n - 1。
(byte 8 0) => (8 . 0)

ldb:

(ldb (byte 8 0) #xabcd) => 171 ;;即0xab,从bit0开始取8个bit
(ldb (byte 8 8) #xabcd) => 205 ;;即0xcd,从bit8开始取8个bit

 

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部