1

Maybe is to easy to answer but i don't know it. I know IEEE-754 is for float values and double but i don't know if is exclusive for those type.

I use this to convert float and works fine i have another code in javascript to revert it. But when used it with integer values it just gives some values and the revert doesn't work as supposed to.

So, this definitely doesn't work for integer values?, i can parse it to float and pass it to IEE754 but i just want to know.

this is the code i use in arduino.

void IEEE754( float val, int pos)
{
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}

also, does anyone has the revert code for arduino?..

1

IEEE 754 is the specification for floating point values. Integers aren't floating point values so this function of yours can have nothing to do with integers.

On an Arduino (8-bit):

  • A float value is 4 bytes in IEEE-754 format.
  • A long value is 4 bytes in little-endian format.
  • An int value is 2 bytes in little-endian format.
  • A byte is a byte.

To convert 4 bytes into a long you can use:

long val = (payload[3] << 24) | (payload[2] << 16) | (payload[1] << 8) | payload[0];

An int value is just the lower two bytes of the same kind of conversion:

int val = (payload[1] << 8) | payload[0];

You can use the same method (albeit backwards) to get the bytes to put in your payload:

long val = 12345678L
payload[0] = val & 0xFF;
payload[1] = (val >> 8) & 0xFF;
payload[2] = (val >> 16) & 0xFF;
payload[3] = (val >> 24) & 0xFF;

You can also use the same technique as your existing function with different datatypes, since all you care about is the byte content not the format or meaning of the bits within it:

void int2payload( int val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 2 ; i++) {
      payload[pos + i] = array[i];
  }
}

void long2payload( long val, int pos) {
  byte* array = (byte*) &val;
  for (int i = 0 ; i < 4 ; i++) {
      payload[pos + i] = array[i];
  }
}
  • Although rather than shifting it's probably more effective to cast to a byte array there too. – Ignacio Vazquez-Abrams Aug 16 '17 at 21:40
  • On an 8 bit system it makes no difference. It's all bytewise access either way. On 16 and 32 bit systems it can make a difference if the architecture has bytewise access operators. – Majenko Aug 16 '17 at 21:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.