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
相關文章
相關標籤/搜索