You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IEEE754单精度浮点数字节表示不一致:C与Common Lisp适配问题

x86_64环境下C与Common Lisp的IEEE754单精度浮点数差异问题

在x86_64 GNU/Linux环境中,使用Common Lisp读取C/C++生成的单精度浮点数二进制文件时,发现通过ieee-floats包的decode-float32函数解析出的浮点数有效位,与C程序读取同一份数据的结果存在细微差异。

经确认,ieee-floats:decode-float32的实现严格符合维基百科中IEEE754单精度浮点数的定义,且在线IEEE-754浮点数转换器的结果也与该函数行为完全一致。

现提出两个核心问题:

  • 为何C版本的读取结果会出现不一致?
  • 如何在Common Lisp中复现C的读取行为?

验证实验代码

C代码(生成随机浮点数及对应字节表示)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int COUNT = 16;

void main () {
  float f;
  uint32_t i;
  char* pf = (char *)&f;
  char* pi = (char *)&i;

  for(int j=0; j<COUNT; j++) {
    f = (float)rand()/(float)(RAND_MAX/2.0) - 1.0;
    pf = (char *)&f;
    pi = (char *)&i;
    memcpy(pi, pf, sizeof(float));
    printf("%9f #x%x\n", f, i);
  }
}

Common Lisp代码(读取数据并对比编码)

(ql:quickload '(:iterate :ieee-floats))

(defun scan (&optional (file "floats_and_bytes.dat"))
  (with-open-file (in file)
    (iter (for f next (read in nil))
          (for b next (read in nil))
          (while (and f b))
          (format t "~9f ~x ~x ~b~%"
                  f
                  (ieee-floats:encode-float32 f)
                  b
                  (- (ieee-floats:encode-float32 f) b)))))

内容的提问来源于stack exchange,提问作者user3414663

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:55:26