Borrar filtros
Borrar filtros

float array to binary string and vice-versa?

1 visualización (últimos 30 días)
Marc
Marc el 17 de Mayo de 2013
Hello, In order to exchange information with an external application, I need to "pack" an array of numbers into a string, and vice-versa. How can I achieve this? I need to do this with 32bit floats and 32bit unsigned integers.
The external application sends the data like following:
float myFloatArray[4];
char* dataToSend=(char*)myFloatArray;
sendData(dataToSend,4*4); // 4*4 is the size of the data
Data is packed as little Endian.
Thanks for any insight!

Respuestas (2)

José-Luis
José-Luis el 17 de Mayo de 2013
Editada: José-Luis el 17 de Mayo de 2013
I don't exactly understand what you are trying to achieve in Matlab. The code you show is C/C++. Also, there are no pointers in Matlab (not explicitely at least). You could save your floats as a binary file, using little endian byte order. There is no need to typecast:
your_float = single(rand(1,4));
%Saving it as binary stream
fid = fopen('myBin.bin','w','l'); %little endian
fwrite(fid,your_float,'single');
fclose(fid);
The you could read that file in your C/C++ code. Or do you actually mean that you want a string of zeros and ones? That is a different thing.

Marc
Marc el 17 de Mayo de 2013
Hello and thank you for your reply.
Actually I have to communicate with a C library. The C library is providing me with a string that contains coded (or packed) floats.
The C library puts the floats into a string according to the little-Endian standard. One 32bit float can be represented as 4 bytes (or chars in the string). It is like sending to Matlab the memory print of that float.
So, as an example, when the C library sends 3 floats, Matlab will receive 3*4 chars, or a string with 12 chars. For example on the C library side:
float my3Floats[3]={0.0f,1.0f,12345678.0f};
char* myStringToSend=(char*)my3Floats;
The 12 chars or byte values of "myStringToSend" contain:
0,0,0,0,0,0,128,63,78,97,60,75
My Matlab program will receive the above string that contains 12 bytes. From those 12 chars I need to rebuild the 3 floats. How do I do that in Matlab, without going through a file?
Basically:
x 32-bit floats in C are put into a x*4 char long string that is sent to Matlab. Matlab takes that string, and extracts 3 float values
Thanks
  1 comentario
José-Luis
José-Luis el 17 de Mayo de 2013
In that case maybe a mex file is what you want. You can create a mex function that accepts a pointer as input and returns the floats as output. You would need to do the relevant typecasting in C.
doc mex

Iniciar sesión para comentar.

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by