浮動小数点数のIEEE754形式への変換
倍精度浮動小数点数をIEEE754形式のビット表現(整数値)にエンコードする方法。
(defun encode-double-float (float) (declare (double-float float)) (multiple-value-bind (fraction exponent sign) (integer-decode-float float) (let ((code 0)) (setf (ldb (byte 1 63) code) (if (plusp sign) 0 1) (ldb (byte 11 52) code) (+ exponent 52 1023) (ldb (byte 52 0) code) fraction) code)))
デコード。
(defun decode-double-float (code) (let ((sign (ldb (byte 1 63) code)) (exponent (ldb (byte 11 52) code)) (fraction (ldb (byte 52 0) code))) (assert (not (and (= exponent #b11111111111) (= fraction 0)))) ; infinity (assert (not (and (= exponent #b11111111111) (/= fraction 0)))); NaN (* (if (zerop sign) 1 -1) (scale-float (+ 1.0d0 (* fraction (expt 2 -52))) (- exponent 1023)))))
実行例。
(encode-double-float 1234.5678d0) --> 4653144502051863213 (format t "~b" *) 100000010010011010010100100010101101101010111001111101010101101 --> NIL (decode-double-float 4653144502051863213) --> 1234.5678d0