Common Lisp二进制操做汇总

1. 文件读取

read-byte:javascript

(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:java

(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:spa

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

logior:code

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

logand:对象

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

logxor:ip

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

byte:element

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

ldb:input

(ldb (byte 8 0) #xabcd) => 171 ;;即0xab,从bit0开始取8个bit
(ldb (byte 8 8) #xabcd) => 205 ;;即0xcd,从bit8开始取8个bit
相关文章
相关标签/搜索