Reputation: 186
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. I'm thinking of making an integer array of size 4 (1 byte at a index per transaction).
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. I'd appreciate any help! Thank you in advance.
Upvotes: 1
Views: 2620
Reputation: 62898
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.
Upvotes: 3