[英]C Converting float to int array
I'm trying to convert a 'float' variable to an integer array as I'm going to send it over an I2C bus and I2C only allows me to do 1 byte transactions at a time. 我正在尝试将“浮点型”变量转换为整数数组,因为我将通过I2C总线发送该变量,而I2C只允许我一次执行1字节事务。 I'm thinking of making an integer array of size 4 (1 byte at a index per transaction).
我正在考虑制作一个大小为4的整数数组(每个事务在索引处为1个字节)。
I'm aware this can simply be done if we want to convert 'float' to 'string' using memcpy() but I want to convert my 'float' variable directly to an int array, then send my array to do operations 1 byte at a time. 我知道如果我们想使用memcpy()将'float'转换为'string'即可简单地做到这一点,但我想将'float'变量直接转换为int数组,然后将其发送给我的数组进行1个字节的操作一次。 I'd appreciate any help!
我将不胜感激! Thank you in advance.
先感谢您。
It's a bit unclear what you really are after, but how about this: 还不清楚您真正追求的是什么,但是如何呢:
// 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];
}
In case you are actually fine with an integer array ( char
is an integer), and don't require the use of the exact int[]
type, then you can just skip that last part of above code. 如果您实际上使用整数数组(
char
是整数)并且不需要使用确切的int[]
类型,则可以跳过上述代码的最后一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.