MATLAB: Dspace producing different result than Simulink when using TYPECAST inside MATLAB Function Block in Simulink 7.7 (R2011a)

simulink

I have a MATLAB function with the following code inside it:
function y = fcn(u)
%#codegen
y =typecast(u,'double')
For example:
>> typecast(42.354887660341, 'uint8')
ans =
147 117 119 245 108 45 69 64
>>
If I feed this UINT8 to the Matlab Fcn Block (created with the Function above), in Simulink I get back the DOUBLE : 42.354887660341
But, with the generated code when I check the same value in DSPACE, I see a totally different value.
Why is this happening?

Best Answer

This has to do with the 'Endianness'. Their is a byte swapping going on somewhere. I.e., converting little-endian to big-endian. You can find more information about 'Endianness' at the wiki:
Endianness
Now to ensure/check that this is the case, we can use 'swapbytes' OR 'flipud' OR 'fliplr' function inside the MATLAB function block. More information on 'swapbytes':
swapbytes:
Now the change inside the MATLAB function block has to be :
y =typecast(swapbytes(u),'double'), OR
y = typecast( fliplr( u ), 'double')
But with this change, please note, the values you will see in Simulink simulation will be incorrect, as we have swapped the bits for Simulink.
Now to make the numbers appear same in simulation, we can use an Environment Controller block, more on that at the following documentation:
Environment Controller: