2

I have a C++ process which has a thread that needs to send floats stored in an array to another process via named pipes. I have constructed the byte array ready for sending but I am not too sure how to get the floats in a form that can be sent over (i.e. how to convert them into bytes).

The other process is a C# process on the same machine and I assume I can use BitConverter to grab the relevant bytes in the incoming byte array and change it into a float but I am not too familiar with C++ and don't know how to change the float to a byte[].

The platform is Windows, I am using Visual Studio 2010 C++.

Jkh2
  • 1,010
  • 1
  • 13
  • 25

3 Answers3

2

Simple enough:

const void *data = &myFloat;
size_t size = sizeof myFloat;

Then use memcpy to move the data where you want it.

  • If I needed to copy the float into my byte array that I will be sending at say index 100, can I copy directly into the large byte array without copying into an intermediate byte array of length 4 using memcpy? – Jkh2 Mar 30 '12 at 14:22
  • yes you can. just give the memcpy an appropriate target address. In fact, it's a one-liner: `char *myBytes; memcpy(myBYtes+100, &myFloat, sizeof myFloat);` (`char *myBytes` rather than `void *` so that I can use pointer arithmetic). –  Mar 30 '12 at 14:28
2

the quick and dirty way is to use a union:

union getBytes
{
    float floatNumber;
    byte bytes[sizeof(float)];
} number;

the BIG caveat is to watch for endianness on the two end machines. Finding out endianness has been solved before many times, so try searching for some resources on that. Just make sure your bytes match up on both sides.

EDIT: changed bytes in union to match size of float on the machine.

Scott M.
  • 7,313
  • 30
  • 39
  • union is about the worst way to do it. What if float is 8 bytes? What if there is padding somewhere? –  Mar 30 '12 at 14:29
  • union is the correct way to do it. it doesn't have problems with strict-aliasing. you just need byte `bytes[sizeof(float)]`. – Eddie Edwards Mar 30 '12 at 14:33
  • im curious how padding would be a problem, as the union should make the elements occupy the same memory. The sizeof(float) part is what i was missing. – Scott M. Mar 30 '12 at 14:33
0

I recommend use this C++ header-only library.

BitConverter

It can convert the bytes to floating-point numbers, and get the bytes of them. More importantly, users can specify the endianness, which is very important if you want to send the bytes to another machine and get the value there.

werewolf
  • 43
  • 4