c - 如何显示 float

标签 c

我个人使用一个函数 show_bytes 如下:

#include<stdio.h>
typedef char *byte_pointer;

void show_bytes (byte_pointer x)
{
        int length = sizeof(float);
        int i;
        for(i = 0;i <length;i++)
        {
                printf("%2x",*(x+i));
                printf("\n");
        }
}

int main()
{
        float obj;
        printf("please input the value of obj:");
        scanf("%f",&obj);
        show_bytes((byte_pointer) &obj);
}

当我输入120.45时,应该是0x42f0e666

please input the value of obj:120.45
66
ffffffe6
fffffff0
42

为什么我使用 %.2x 时 e6 和 f0 之前有这么多 'f'。

最佳答案

你的功能应该是:

void show_bytes (byte_pointer x)
{
   int i;
   for(i = 0; i <sizeof(float); i++)
   {
      printf("0x%2X\n", (unsigned int)(*(x++) & 0xFF));
   }
}

typedef uint8_t *byte_pointer;

void show_bytes (byte_pointer x)
{
   int i;
   for(i = 0; i <sizeof(float); i++)
   {
      printf("0x%2X\n", *(x++));
   }
}

在您的代码中,问题在于指针类型是 signed 并被 printf 提升为 signed int

%2X 格式不限制输出位数,只告诉 printf 结果字符串必须至少 2 个字符长。

  • 第一个解决方案:将值提升为 signed int 但传递的 值被截断到 LSB。
  • 第二个例子:值被指针类型截断,即 是 unsigned char

规则是: 对于原始访问内存,始终使用无符号类型。

关于c - 如何显示 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35057737/

相关文章:

c - 回文 - 删除 goto

c - 如何静态编译lighttpd模块

c - 在非结构或 union 中请求成员 's'

c - 在 C 中分配内存的所有方法是什么?它们有何不同?

python - 是否可以使用 Cython 将指向编译时未知函数的 C 函数指针传递给 C 函数?

c - 如何可维护地确定 sizeof(struct ...)s?

c - 请解释一下C程序的这个功能是如何工作的?

c++ - 在不知道返回类型的情况下通过地址调用 C++ 中的函数

c - 为什么 char[] 在堆栈上,而 char * 在堆上?

c - 返回语句 C 上的 SegFault