C中浮点数的字节数

Bytes of floating point number in C

我正在阅读《计算机系统:程序员的视角》(Bryant & O'Hallaron)。 在第 2 章图 2.4 中显示了以下代码

#include <stdio.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len){
  int i;
  for(i = 0; i < len; i++)
    printf(" %.2x", start[i]);
  printf("\n");
}

void show_int(int x){
  show_bytes((byte_pointer) &x, sizeof(int));
}

void show_float(float x) {
  show_bytes((byte_pointer) &x, sizeof(float));
}

void show_pointer(void *x){
  show_bytes((byte_pointer) &x, sizeof(void *));
}

图 2.4 打印程序对象字节表示的代码。此代码使用 强制转换以规避类型系统。类似的功能很容易为其他数据定义 类型

然后用下面的方法

void test_show_bytes(int val) {
int ival = val;
float fval = (float) ival;
int *pval = &ival;
show_int(ival);
show_float(fval);
show_pointer(pval);
}

按照书上的说法,如果值为12345

,这个测试方法应该在linux64上打印以下内容
39 30 00 00
00 e4 40 46
b8 11 e5 ff ff 7f 00 00

然而,当我 运行 代码时,我得到以下结果

39 30 00 00
00 00 00 00
d8 d6 54 c3 fd 7f 00 00

我使用的是 gcc 版本 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04) 我 运行ning 基于书中示例的代码 我是 C 的新手,知道为什么我的结果不同吗?

#include <stdio.h>

typedef unsigned char *byte_pointer;

nt main(){
  int val =  12345;
  test_show_bytes(val);
}

void test_show_bytes(int val) {
  int ival = val;
  float fval = (float) ival;
  int *pval = &ival;
  show_int(ival);
  show_float(fval);
  show_pointer(pval);
}


void show_bytes(byte_pointer start, int len){
  int i;
  for(i = 0; i < len; i++)
    printf(" %.2x", start[i]);
  printf("\n");
}

void show_int(int x){
  show_bytes((byte_pointer) &x, sizeof(int));
}

void show_float(float x) {
  show_bytes((byte_pointer) &x, sizeof(float));
}

void show_pointer(void *x){
  show_bytes((byte_pointer) &x, sizeof(void *));
}
在看到 show_float(float x) 的函数定义之前使用

show_float(fval); - 禁忌。不要那样做。使所有编译器警告更加高效。

编译器将定义猜测为 show_float(double x),因此在 show_float(fval); 调用期间传递了错误的信息。

谢谢,解决了。

是的,我收到了很多关于函数隐式声明和类型冲突的警告。 我对错误级别日志下的任何内容几乎视而不见,我的错。 我将检查默认参数提升在 C 中的含义 按顺序放置函数声明解决了这个问题。我最初只是猜到了主要功能的位置。愚蠢的猜测,我以前只在 OOP 语言中使用过 main(),应该阅读文档。

#include <stdio.h>

typedef unsigned char *byte_pointer;

void show_bytes(byte_pointer start, int len){
  int i;
  for(i = 0; i < len; i++)
    printf(" %.2x", start[i]);
  printf("\n");
}

void show_int(int x){
  show_bytes((byte_pointer) &x, sizeof(int));
}

void show_float(float x) {
  show_bytes((byte_pointer) &x, sizeof(float));
}

void show_pointer(void *x){
  show_bytes((byte_pointer) &x, sizeof(void *));
}

void test_show_bytes(int val) {
  int ival = val;
  float fval = (float) ival;
  int *pval = &ival;
  show_int(ival);
  show_float(fval);
  show_pointer(pval);
}

int main(){
  int val =  12345;
  test_show_bytes(val);
}