Adding 2s compliment notation to a function

4 views (last 30 days)
I have a function as detailed below:
function [A B C] = elevation (d,p,t)
FC = 360;
d = hex2dec (d);
p = hex2dec (p);
t = hex2dec (t);
A = (d*0.5*FC/2^18);
B = (p*0.5*FC/2^15);
C = (t*0.5*FC/2^15);
If i call the function using [A B C] = elevation ('FFE38D', 'FC71', 'FC6D');
The above function would output decimal values 16769933, 64625, and 64621 respectively, however i would like the 2s compliment values -7282, -910 and -914. Preferably i would have the 2s compliment code wrote into the function rather than the command window.
Any help is much appreciated. Thanks in advance
  5 Comments
Darren
Darren on 13 Feb 2013
Yes Walter you are correct, the first word is 24 bits and the second and third are 16 bits.
So basically i'm looking for:
[A B C] = elevation ('FFE38D', 'FC71', 'FC6D'); % should equal negative values
[A B C] = elevation ('001C72', '038E', '0392'); % should equal positive values
Darren
Darren on 13 Feb 2013
In addition, i have looked searched through previous answers and tried the following:
function [A B C] = training2s(d,p,t)
FC = 360;
typecast(uint24(hex2dec(d),'int24'))
typecast(uint16(hex2dec(p,t),'int16'))
d = hex2dec (d);
p = hex2dec (p);
t = hex2dec (t);
A = (d*0.5*FC/2^18);
B = (p*0.5*FC/2^15);
C = (t*0.5*FC/2^15);
end
However the above code results in an error in the typecast lines.
Any help is much appreciated. Thanks

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Feb 2013
d = hex2dec (d);
if d > 2^23-1; d = 2^24 - d; end
p = hex2dec (p);
if p > 2^15-1; p = 2^16 - p; end
t = hex2dec (t);
if t > 2^15-1; t = 2^16 - t; end
  3 Comments
Walter Roberson
Walter Roberson on 13 Feb 2013
Yes, sorry, mental mistake on my part. Should be the negatives of those, such as d - 2^24
Darren
Darren on 14 Feb 2013
Thanks for all your help Walter! It works perfectly

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!