1

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.

2
  • 1
    It's all just arrangements of bits in memory. You need to know what sort of arrangements is expected on the other side of I2C bus. Commented Jul 26, 2019 at 10:32
  • I see you've also asked before: electronics.stackexchange.com/questions/450201/… Commented Jul 26, 2019 at 10:33

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.