Casting uint16 to int16 in Simulink

Hi Mathworks Community
do you know a good implementation for casting an uint16 to an int16.
I'm using Simulink to program a dSpace MicroAutobox II and receiving two 8bit values via CAN-Interface representing a signed integer in Two's complement representation.
Example 0100 1001 0010 1010 = 18730; 1010 1000 0010 1010 = -22486
Is there a native method to do so? Yet I'm using a self-written MATLAB Code looking like this:
function n_actual = fcn(data1, data2)
% data2 contains bits 8 - 15, data1 0 - 7 little endian
%#codegen
tmp = uint16(data2)*2^8+uint16(data1);
if(tmp > 2^15) % negativ value
% tip signed bit
% (2^16-1) subtracted by tmp for int16
% (tmp+1)*(-1) add 1 for the previous
% step to stay in range of value and negate
tmp = -((32767-int16(tmp-2^15))+1);
else
tmp = int16(tmp);
end
n_actual = tmp;
The typecast methode simply takes the number and matches it on the range of values to cast to. -20 would then be 32767, therefore not interesting for my use, am I right.
Hopefully my English is not to bad to understand my issue.
Thanks for your reply
Matthias

1 commentaire

Matthias
Matthias le 25 Mar 2013
I forgot to mention why it's important to handle it as efficient as possible. The Autobox is a trip computer (real time) with few resources and therefore every avoided computation is a good computation.

Connectez-vous pour commenter.

Réponses (0)

Question posée :

le 25 Mar 2013

Community Treasure Hunt

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

Start Hunting!

Translated by