为 int 和 int 转换为 float

标签 c pointers casting floating-point

指针有点困难。我必须将一个 float 存储在一个无符号整数数组中,并且能够将其取出。

我知道有一种特殊的方式来转换它,所以我不重新排序这些位,我认为当我想将它放入数组时这是正确的存储方式:

float f = 5.0;
int newF = (int *) f;
arrayOfInts[0] = *newF

这似乎成功地将值存储在数组中。 但是,在某些时候我必须将值从整数数组中拉回,这就是我的困惑所在(假设我正确地输入到数组中)

float * f = (float *) arrayOfInts[0]
int result = *f;

然而,这给了我警告:'cast to pointer from integer of different size'

如果没有某种长时间的转换,我真的想不出如何解决这个问题……这似乎不对……

我不想丢失值或损坏位..显然它会丢失小数点精度..但我知道他们有一些安全来回转换的方法

最佳答案

I have to store a float in an array of unsigned ints and be able to pull it out.

使用unionunsigned char[]unsigned char 被指定为没有任何填充并且所有位组合都是有效的。许多其他数字类型并不总是如此。通过用 unsigned char[] 覆盖 float,代码可以一次检查一个 float 的每个“字节”。

union {
  float f;
  unsigned char uc[sizeof (float)];
} x;

// example usage
x.f = 1.234f;
for (unsigned i = 0; i<sizeof x.uc; i++) {
  printf("%u:%u\n", i, 1u*x.uc[i]);
}

示例输出:您的可能会有所不同

0:182
1:243
2:157
3:63

float --> unsigned char[] --> float 总是安全的。

unsigned char[] --> float --> unsigned char[] 作为 的组合并不总是安全的unsigned char[] 可能没有有效的 float 值。

避免指针技巧和转换。存在对齐和大小问题。

// Poor code
float f = 5.0f;
int newF = *((int *) &f);  // Conversion of `float*` to `int*` is not well specified.

代码也可以覆盖固定宽度的无填充类型,如 (u)int32_t 如果它们存在(它们通常存在)并且大小匹配。

#include <stdint.h>
union {
  float f;
  uint32_t u32;
} x32;


#include <assert.h>
#include <inttypes.h>

// example usage
assert(sizeof x32.f == sizeof x32.u32);
x32.f = 1.234f;
printf("%" PRNu32 "\n", x32.u32);
}

示例输出:您的可能会有所不同

1067316150

关于为 int 和 int 转换为 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43618299/

相关文章:

c - 使用 memcpy 进行内联线程调度

c++ - 返回 vector 元素 C++ 的地址

sql - TSQL 尝试清理杂乱的字符串字段并将其转换为小数以执行 SUM 函数

c++ - 将波形文件读入带符号的 float 组

c++ - 找不到任何 GLU 文档

c++ - 前向 FFT 图像和后向 FFT 图像以获得相同的结果

pointers - 指向具有保存类型的接口(interface)的指针

C++编译时断言BASE是EXTENDED的基类并且具有相同的内存地址

c - 在 Windows 中获取另一个进程的命令行参数

c - C 中的指针 : Difference in the two declarations