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,则此测试方法应在linux 64上打印以下内容

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),我正在运行的代码基于我对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 *));
}
chux-恢复莫妮卡

show_float(fval);在看到功能定义之前使用show_float(float x)-否。不要那样做 使所有编译器警告更加有效。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将浮点数转换为字节数组

来自分类Dev

浮点数到字节数组的转换

来自分类Dev

在OCaml中,如何从字节数组创建浮点数?

来自分类Dev

在Python 3中将字节数组转换为浮点数组

来自分类Dev

C函数将浮点数转换为字节数组

来自分类Dev

如何在C ++中将浮点数组转换为字节数组(Arduino)

来自分类Dev

如何在c#中将浮点数组转换为字节数组?

来自分类Dev

有效将浮点数组转换为字节数组

来自分类Dev

浮点数组类型的变量引用的值如何具有字节数组类型?

来自分类Dev

如何将有符号字节数组转换为浮点数?

来自分类Dev

浮点数,整数和str到字节数组-python

来自分类Dev

Java将负浮点数转换为字节数组

来自分类Dev

浮点数的字节序

来自分类Dev

MATLAB中的单精度浮点到字节数组

来自分类Dev

字节数组到浮点转换C#

来自分类Dev

Memcpy与C ++中的浮点数

来自分类Dev

在Pro * C中处理浮点数

来自分类Dev

如何计算C中的浮点数?

来自分类Dev

C中的冒泡排序浮点数

来自分类Dev

Memcpy与C ++中的浮点数

来自分类Dev

fscanf() 在 C 中舍入浮点数

来自分类Dev

在Swift中获取浮点数的原始字节

来自分类Dev

Common Lisp中浮点数的字节表示

来自分类Dev

从字节数组C#中读取特定的字节

来自分类Dev

字节数组中的字节数

来自分类Dev

在C / C ++中以字节数组读写文件

来自分类Dev

Java中的浮点数

来自分类Dev

bash中的浮点数

来自分类Dev

反转浮点数 C