Effacer les filtres
Effacer les filtres

float array to binary string and vice-versa?

1 vue (au cours des 30 derniers jours)
Marc
Marc le 17 Mai 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!
  1 commentaire
James Tursa
James Tursa le 17 Mai 2013
Are you using loadlibrary for this?

Connectez-vous pour commenter.

Réponses (2)

José-Luis
José-Luis le 17 Mai 2013
Modifié(e) : José-Luis le 17 Mai 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 le 17 Mai 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 commentaire
José-Luis
José-Luis le 17 Mai 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Write C Functions Callable from MATLAB (MEX Files) dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by