MATLAB: Is it possible to store a array of single precision type into unsigned char

data conversiondata types

In my existing parsing file there is a assignment
plhs[0] = mxCreateNumericMatrix( nof_data_values, elem_count, mxSINGLE_CLASS ,mxREAL);
where the number of data values is 6 and element count depends upon the no. of samples reading in single precision and in later in that same code another assignment is there
unsigned char* output_mat = reinterpret_cast< unsigned char* >(mxGetData(plhs[0]));
where after reinterpret casting of plhs[0] is getting stored in a matrix.
How is it possible I tried the same but failed using matlab.

Best Answer

No, you cannot do that directly in MATLAB. MATLAB does not have unsigned char. MATLAB has char(), which is a non-numeric datatype (neither signed nor unsigned) which is 16 bits wide per element. char() are automatically promoted to double when used in arithmetic statement as if they were small positive integers.
If you want to convert an array of single into uint8 then use
typecast(YourArrayOfSingle, 'uint8')
If you want to convert an array of single into char then use either
char(typecast(YourArrayOfSingle, 'uint16'))
or
char(typecast(YourArrayOfSingle, 'uint8'))
Remember, though, that it is common for bytes inside a single precision number to map into unicode code points for which there is no standard glyph.