C 将 float 转换为 int 数组

C Converting float to int array

我正在尝试将 'float' 变量转换为整数数组,因为我将通过 I2C 总线发送它,而 I2C 一次只允许我进行 1 字节的事务处理。我正在考虑制作一个大小为 4 的整数数组(每个事务的索引处有 1 个字节)。

我知道如果我们想使用 memcpy() 将 'float' 转换为 'string' 可以简单地完成此操作,但我想将我的 'float' 变量直接转换为 int数组,然后发送我的数组以一次执行 1 个字节的操作。我将不胜感激任何帮助!提前谢谢你。

有点不清楚你到底在追求什么,但是这个怎么样:

// original float value
float value = 42.0f;

// intermediate char buffer to allow memcpy of float's bytes
char charbuf[sizeof float];
memcpy(charbuf, &value, sizeof float);

// the actual int array you want, use for loop to copy the ints
int intarray[sizeof float];
for(unsigned index = 0; index < sizeof float; ++index) {
    intarray[index] = charbuf[index];
}

如果您实际上可以使用整数数组(char 是一个整数),并且不需要使用确切的 int[] 类型,那么您可以跳过最后一个以上代码的一部分。