Question

I am writing an C++ Application which reads several voltages from a device. I receive these measurements in an float[] and I want to send this array via UDP to a MATLAB-Script.

the C++-function sendto needs to get an char[] buffer and I really have no idea how to convert the float[] into a char[] buffer so i can reassemble it easily in MATLAB. Any Ideas?

Another problem i encountered is that line

addr.sin_addr = inet_addr("127.0.0.1");

inet_addr returns an unsigned long, but my compiler tells me that the = operator does not accept an unsigend long datatype on its right side. Any Iideas about this?

Was it helpful?

Solution

You can always treat any object variable as a sequence of bytes. For this very purpose, it is explicitly allowed (and does not violate aliasing or constitute type punning) to reinterpret any object pointer as a pointer to the first element in an array of bytes (i.e. any char type).

Example:

T x;
char const * p = reinterpret_cast<char const *>(&x);

for (std::size_t i = 0; i != sizeof x; ++i) { /* p[i] is the ith byte in x */ }

For your case:

float data[N];
char const * p = reinterpret_cast<char const *>(data);

write(fd, p, sizeof data);

OTHER TIPS

Decide if you want to format the UDP messages as text or binary. If text, you can convert floats to strings using boost::lexical_cast. You can frame the string valus in the UDP message any way you want (comma separated values, newline separated, etc.), or you could use a known format such as JSON.

If you want to transmit binary data, select an known format, such as XDR which is used by ONC RPC and use existing library tools to create the binary messages.

As for the inet_addr error, addr.sin_addr is a struct in_addr. You need to assign the result to the s_addr member of the sin_addr struture like this:

addr.sin_addr.s_addr = inet_addr("127.0.0.1");

There are two questions in your post. I believe that is not how it's supposed to be.

As for float[]->byte[] conersion - you should check how matlab stores it's floating point variables. If, by any chance, it uses the same format as you compiler, for your computer setup etc etc only, you can simply send these as a byte array[]. In any other case - incompatible float byte format, multiple machines - you have to write a manual conversion. First each float to (for example) string, then many floats. Your line could look like:

1.41234;1.63756;456345.45634

As for the addr.sin_addr - I think you are doing it wrong. You should access

addr.sin_addr.s_addr = inet_addr("1.1.1.1");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top