如何使用Chicken Scheme读写二进制浮点数?

时间:2011-02-03 02:24:00

标签: binary scheme chicken-scheme

我正在阅读使用Chicken的二进制数据格式,到目前为止,我已经通过像(fx+ (fxshl (read-byte) 8) (read-byte))(Big Endian)这样的工作来完成工作。

如何读写浮点数?我必须能够读写IEEE 754-2008 32位和64位二进制浮点数。

1 个答案:

答案 0 :(得分:0)

到目前为止,我还没有找到任何好的库来实现这一目标,但我已经将一些有效的东西整合在一起。请注意,我只能将read-byteread-string作为输入操作。

  ;;
  ;; These are some unfun C routines to convert 4 int-promoted bytes to a float
  ;; by manually assembling the float using bitwise operators
  ;;
  ;; Caveat! These will only work on platforms in which floats are 32-bit Big
  ;; Endian IEEE754-2008 numbers and doubles are 64-bit Big Endian IEEE754-2008
  ;; numbers! Also, stdint.h.
  ;;
  (define (readFloat)
    (let ([c-read-float
            (foreign-lambda* float
              ((int i1)
               (int i2)
               (int i3)
               (int i4))
               "uint8_t b1 = (uint8_t) i1;
                uint8_t b2 = (uint8_t) i2;
                uint8_t b3 = (uint8_t) i3;
                uint8_t b4 = (uint8_t) i4;

                uint32_t i = 0;

                i = b1;
                i = (i << 8) | b2;
                i = (i << 8) | b3;
                i = (i << 8) | b4;

                float f = *(float*)&i;

                C_return(f);")])
        (let* ([i1 (read-byte)]
               [i2 (read-byte)]
               [i3 (read-byte)]
               [i4 (read-byte)])
          (c-read-float i1 i2 i3 i4))))