Convert float type to two short (high & low bytes)

1

I transfer data through serial port. on decoding side. I'm coding on transferring side follow the code from receiving side. I must encode data from float type (4 bytes) to high part and low part (short type) then transfer them.

I had the decoding code. What i must do on encoding side.

I tried convert signed int si from float realSi but it was wrong. I got value 0 of signed int si. below is decoding code.

unsigned short siH = msg->getDataWordArray()[1]
unsigned short siL = msg->getDataWordArray()[2]
signed int si = (siH << 16) | (siL & 0x0000ffff)
float realSi = (float)((float)si)*180/1073741824);
c++
arrays
decode
encode
converters
asked on Stack Overflow Jan 22, 2019 by Vũ Quang Hòa • edited Jan 22, 2019 by gameon67

1 Answer

0

One way to do this would be to use a union, as shown in the example code below. Keep in mind that this will only work if the computers on both sides of the serial connection are using the same floating-point format and the same endian-ness. If they aren't, you'll need to add additional translation logic to handle those differences.

#include <stdio.h>

union Foo
{
   unsigned short asShorts[2];
   float asFloat;
};

int main(int, char * *)
{
   // Convert a float into two shots
   Foo foo;
   foo.asFloat = 3.14159f;
   printf("For float value %f, the shorts are %u and %u\n", foo.asFloat, foo.asShorts[0], foo.asShorts[1]);

   // [... send the two asShorts values across the serial port here...]


   // Imagine this is the receiving-side code (after having received the two shorts)
   const unsigned short s1 = foo.asShorts[0];
   const unsigned short s2 = foo.asShorts[1];

   // Convert the two shorts back into a float
   Foo bar;
   bar.asShorts[0] = s1;
   bar.asShorts[1] = s2;
   printf("For shorts %u and %u, the float value is %f\n", s1, s2, bar.asFloat);


   return 0;
}

... btw, if you'd prefer to send/receive bytes rather than shorts, you could change the union to look like this instead:

union Foo
{
   unsigned char asBytes[4];
   float asFloat;
};
answered on Stack Overflow Jan 22, 2019 by Jeremy Friesner • edited Jan 22, 2019 by Jeremy Friesner

User contributions licensed under CC BY-SA 3.0